set_new_handler is used to test if new has worked.
I have noticed that the function does not seem to operate in the same way with all compilers. Please assume I am talking about Solaris for the rest of this page.
When new fails, a special error recovery function is called. This function will issue a message and then terminate your program. With set_new_handler() you can control what happens when an error occours. For example, you could issue your own message, close files, free some memory or try again.
Here is the first example.
#include <new.h>
main()
{
char *MegaByte;
MegaByte = new char[1024*1024];
}
|
This code attempts to allocate 1Mb of storage. If it fails, the default error handler is called and the program terminates.
The next example starts to introduce set_new_handler()
#include <new.h>
#include <iostream.h>
main()
{
char *MegaByte;
set_new_handler(0);
MegaByte = new char[1024*1024];
if (MegaByte == NULL)
{
cerr << "Unable to allocate 1MByte." << endl;
}
}
|
Normally MegaByte holds the address of the reserved storage. If set_new_handler() is given a value of zero, and new fails, MegaByte is also set to zero.
The next example shows the real power of set_new_handler
#include <new.h>
#include <iostream.h>
void NewError();
main()
{
char *MegaByte;
set_new_handler(NewError);
MegaByte = new char[1024*1024];
}
void NewError()
{
cerr << "Unable to allocate 1MByte." << endl;
}
|
Here set_new_handler is passed the address of a function. When new fails now, NewError is called. When NewError completes, the new statement is retried. This example has the advantage of being able to call new as often as it likes and there only.
This example tidies up a little by terminating the program within NewError
#include <new.h>
#include <iostream.h>
#include <stdlib.h>
void NewError();
main()
{
char *MegaByte;
set_new_handler(NewError);
MegaByte = new char[1024*1024];
}
void NewError()
{
cerr << "Unable to allocate 1MByte." << endl;
exit(0);
}
|
| Top | Master Index | C++ Keywords | Functions |