function
std::set_new_handler
<new>
new_handler set_new_handler (new_handler new_p) throw();
Set new handler function
Sets
new_p as the
new handler function.
The
new handler function is the function that is called by functions
operator new or
operator new[] when they are not successful in an attempt to allocate memory.
The
new handler function can make more storage available for a new attempt to allocate the storage. If, and only if, the function succeeds in making more storage avaible, it may return. Otherwise it shall either throw a
bad_alloc exception (or a derived class) or terminate the program with
cstdlib's
abort or
exit functions.
If the
new handler function returns (i.e., it made more storage available), it can be called again if the
operator new or
operator new[] function is again not successful attempting to allocate the storage. This may repeat itself until either the allocation is successful or the
handler function fails.
Parameters
- new_p
- Function that takes no parameters and returns void.
The function can make more storage available or throw an exception or terminate the program.
new_handler is a function pointer type taking no parameters and returning void.
Return value
The value of the current
new_handler function if this has been previously set by this function, or a null pointer if this is the first call to
set_new_handler.
new_handler is a function pointer type taking no parameters and returning
void.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// new_handler example
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
void no_memory () {
cout << "Failed to allocate memory!\n";
exit (1);
}
int main () {
set_new_handler(no_memory);
cout << "Attempting to allocate 1 GiB...";
char* p = new char [1024*1024*1024];
cout << "Ok\n";
delete[] p;
return 0;
}
|
Possible output:
Attempting to allocate 1 GiB... Ok
|
See also
- new_handler
- Type of new handler function (type)
- bad_alloc
- Exception thrown on failure allocating memory (class)
- operator new
- Allocate storage space (function
)