函数原型:
new_handler set_new_handler (new_handler new_p) throw();
它的参数是一个指针,指向new无法分配足够空间时改被调用的函数,返回值也是个指针,指向
set_new_handler被调用前正在执行的那个new-handler函数。
当perator无法申请到足够内存时,它会反复调用new_handler函数,知道找到足够内存,下面的例子new操作无法申请1G内存时,直接调用no_memory,然后执行exit退出程序。
// new_handler example
#include <iostream> // std::cout
#include <cstdlib> // std::exit
#include <new> // std::set_new_handler
void no_memory () {
std::cout << "Failed to allocate memory!\n";
std::exit (1);
}
int main () {
std::set_new_handler(no_memory);
std::cout << "Attempting to allocate 1 GiB...";
char* p = new char [1024*1024*1024];
std::cout << "Ok\n";
delete[] p;
return 0;
}
结果:
Attempting to allocate 1 GiB...Failed to allocate memory!