Home > Backend Development > C++ > How to Universally Override Global `new` and `delete` Operators in Large Codebases?

How to Universally Override Global `new` and `delete` Operators in Large Codebases?

Barbara Streisand
Release: 2024-11-03 13:08:02
Original
701 people have browsed it

How to Universally Override Global `new` and `delete` Operators in Large Codebases?

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>
Copy after login

Including the header is not required as the declarations for operator new and operator delete are hardcoded into the language. However, names such as std, std::bad_alloc, and std::size_t may need to be declared.

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>
Copy after login

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!

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