Namespaces
Variants
Actions

Replacement functions

From cppreference.com
< cpp‎ | language
 
 
C++ language
General topics
Conditional execution statements
Iteration statements (loops)
Jump statements
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
Casts
Memory allocation
Class-specific function properties
Special member functions
Miscellaneous
 
 

Certain functions for which a definition is supplied by the implementation are replaceable . A C++ program may provide a definition with the signature of a replaceable function, called a replacement function . The replacement function, if provided, is used instead of the default version supplied by the implementation. Such replacement occurs prior to program startup.

If a declaration of the replacement function does not satisfy any of the following conditions, the program is ill-formed, no diagnostic is required:

  • It is not inline.
  • It is attached to the global module.
  • It has C++ language linkage.
  • It has the same return type as the replaceable function.
  • If the replaceable function is declared in a standard library header, it would be valid as a redeclaration of the declaration in that header.

Core language

It is implementation-defined whether the contract-violation handler ::handle_contract_violation is replaceable.

(since C++26)

[edit] Standard library

The following standard library functions are replaceable, and the description of function semantics apply to both the default version defined by the C++ standard library and the replacement function defined by the program:

allocation functions
(function) [edit]
deallocation functions
(function) [edit]
checks whether a program is running under the control of a debugger
(function) [edit]

[edit] Example

Uses a replacement allocation function:

Run this code
#include <cstddef>
#include <new>
#include <print>
 
// replacement function
void* operator new (std::size_t count)
{
 std::print ("Replaced!");
 return nullptr;
}
 
int main()
{
 int* ptr = new int; // invokes the replacement version defined by the program
}

Output:

Replaced!
Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/replacement_function&oldid=181097"

AltStyle によって変換されたページ (->オリジナル) /