Overriding Global New & Delete Operators Effectively
Problem:
Replacing the global new and delete operators to use custom memory management presents challenges in large-scale codebases. Including the header file containing the overloads in every file is impractical. How can one ensure universal adoption of these overloads?
Solution:
Overriding new and delete operators is a process done at link time. By creating a separate translation unit (TU) that defines the operators and linking it into the project, one can replace the default operators globally without modifying the existing codebase.
Code Sample:
Here is an example of a TU defining the new and delete operators:
<code class="cpp">// optional_ops.cpp void * operator new(std::size_t n) throw(std::bad_alloc) { //... } void operator delete(void * p) throw() { //... }</code>
Including the
Alternative for C 11 and Later:
C 11 introduces a simpler way to define the new overload, using decltype(sizeof(0)) to determine the type of the size parameter:
<code class="cpp">void * operator new(decltype(sizeof(0)) n) noexcept(false) { //... }</code>
The above is the detailed content of How to Universally Override Global `new` and `delete` Operators in Large Codebases?. For more information, please follow other related articles on the PHP Chinese website!