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()终止了程序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值