An additional feature for handling new
failures is function set_new_handler
(prototyped in standard header <new>
). This function takes as its argument a pointer to a function that takes no arguments and returns void
. This pointer points to the function that will be called if new
fails. This provides you with a uniform approach to handling all new
failures, regardless of where a failure occurs in the program. Once set_new_handler
registers a new handler in the program, operator new
does not throw bad_alloc
on failure; rather, it defers the error handling to the new
-handler function.
If new
allocates memory successfully, it returns a pointer to that memory. If new
fails to allocate memory and set_new_handler
did not register a new
-handler function, new
throws a bad_alloc
exception. If new
fails to allocate memory and a new
-handler function has been registered, the new
-handler function is called. The new
-handler function should perform one of the following tasks:
1. Make more memory available by deleting other dynamically allocated memory (or telling the user to close other applications) and return to operator new
to attempt to allocate memory again.
2. Throw an exception of type bad_alloc
.
3. Call function abort
or exit
(both found in header <cstdlib>
) to terminate the program. These were introduced in Section 9.7.
Figure 17.6 demonstrates set_new_handler
. Function customNewHandler
(lines 9–13) prints an error message (line 11), then calls abort
(line 12) to terminate the program. The output shows that the loop iterated four times before new
failed and invoked function customNewHandler
. Your output might differ based on the physical memory, disk space available for virtual memory on your system and your compiler.