Handling new allocation failure
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.
Your new handler must perform one of the following:
- obtain more storage for memory allocation, then return
- throw an exception of type std::bad_alloc or a class derived from std::bad_alloc
- call either abort() or exit()
The set_new_handler() function has the
prototype:
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 if LANGLVL(NEWEXCP) is in effect.
- new returns a NULL pointer if LANGLVL(NONEWEXCP) is in effect.
The following program fragment shows how you could use set_new_handler() to
return a message if the new operator cannot allocate
storage:
#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 ...
}
If the program fails because new cannot
allocate storage, the program exits with the message:
Operator new failed:
no storage is available.


