wiki:hpp-new
<new>
<new> defines operator new and operator delete for memory allocation. You can overload them for custom allocation behavior or set a custom new_handler function to be called if allocation fails.
Most code never needs this; just use smart pointers from <memory>.
Example
This example sets a custom new_handler to be called if memory allocation fails, though modern code uses smart pointers instead.
// compile: g++ -std=c++11 -o newexample newexample.cpp // run: ./newexample // description: custom new_handler #include <new> #include <iostream> void handle_out_of_memory() { std::cout << "out of memory!\n"; std::exit(1); } int main() { std::set_new_handler(handle_out_of_memory); try { int* p = new int; std::cout << "allocated successfully\n"; delete p; } catch (const std::bad_alloc&) { std::cout << "caught bad_alloc\n"; } return 0; }
wiki/hpp-new.md · Last modified: by 127.0.0.1
