Home > Backend Development > C++ > body text

How Can I Override the Global `new` and `delete` Operators in C ?

Barbara Streisand
Release: 2024-10-30 03:12:03
Original
847 people have browsed it

How Can I Override the Global `new` and `delete` Operators in C  ?

Overriding Global Operators: Replacing new and delete

In a complex codebase, ensuring consistent use of custom new and delete operators can be challenging. One issue is that external libraries and STL usage may bypass custom memory management.

Instead of including overloads in multiple files, a global replacement can be achieved. Link a separate translation unit (TU) that defines these operators. This TU provides the following functions:

<code class="cpp">void * operator new(std::size_t n) throw(std::bad_alloc);
void operator delete(void * p) throw();</code>
Copy after login

Including or similar headers may be necessary to resolve standard library names. In C 11 and above, decltype(sizeof(0)) can replace std::size_t and dynamic exception specifications can be omitted.

<code class="cpp">void * operator new(decltype(sizeof(0)) n) noexcept(false);</code>
Copy after login

By linking this TU, the custom new and delete operators become active throughout the program, ensuring consistent use and improved diagnostic capabilities.

The above is the detailed content of How Can I Override the Global `new` and `delete` Operators in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!