Home  >  Article  >  Backend Development  >  How Can I Override the Global `new` and `delete` Operators in C ?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 03:12:03848browse

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>

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>

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!

Statement:
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