When the new operator creates a new object, it calls the operator new() or operator new[]() function to obtain the needed storage.
When new cannot allocate storage to create a new object, it calls a new handler function if one has been installed by a call to set_new_handler(). The std::set_new_handler() function is declared in the header <new>. Use it to call a new handler you have defined or the default new handler.
typedef void(*PNH)(); PNH set_new_handler(PNH);
set_new_handler() takes as an argument a pointer to a function (the new handler), which has no arguments and returns void. It returns a pointer to the previous new handler function.
If you do not specify your own set_new_handler() function, new throws an exception of type std::bad_alloc.
#include <iostream> #include <new> #include <cstdlib> using namespace std; void no_storage() { std::cerr << "Operator new failed: no storage is available.\n"; std::exit(1); } int main(void) { std::set_new_handler(&no_storage); // Rest of program ... }
Operator new failed: no storage is available.