C++ 中new handler的使用

operator new没有能力为你分配出你所申请的memory,会抛出一个std::bad_alloc exception。某些老版本的编译器则是返回0。
也可以让编译器不抛出异常,只返回0,做法:`new (nothrow)Foo;

C++在抛出异常之前(不止一次)调用一个由程序员知道的handle。(C++在new失败的时候,会调用程序要指定的函数)
形式为:

typedef void(* new_handler)();
new_handler set_new_handler(new_handler p) throw();

设计良好的new handler 只有两个选择:
1. 让更多memory可用(调用了程序员指定的handler,表示内存基本用完了,程序员可以选择释放一些其他的内存,C++会再次尝试new)
2. 调用abort()或exit()

例子

#include <iostream>
using namespace std;

void noMoreMemory() {
    cerr << "out of memory" << endl;
    abort(); //如果不终止程序,将一直重复调用该函数
}

int main(int argc, char *argv[]) {
    set_new_handler(noMoreMemory); //new 失败的时候会调用该函数

    int* p = new int[10000000000000000];
    assert(p);

    p = new int[100000000000000000];
    assert(p);

    return 0;
}

输出结果:
Terminated due to signal: ABORT TRAP (6)
Untitled(4722,0x7fffab16e340) malloc: *** mach_vm_map(size=40000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
out of memory

对于上面的输出,不同的编译或者不同版本的编译器,可以输出的结果不同。但是我的编译器输出了out of memory,并且调用abort()终止了程序。

猜你喜欢

转载自blog.csdn.net/lmb1612977696/article/details/80035323