Home > Article > Backend Development > 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
<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!