Item 49: Understand the behavior of the new-handler(Effective C++)

set_new_handler allows you to specify a function to be called when memory allocation requests cannot be satisfied.
   Nothrow new is of limited utility, because it applies only to memory allocation; subsequent constructor calls may still throw exceptions.

 1  #include  < iostream >
 2  using   namespace  std;
 3 
 4  class  Foo
 5  {
 6  public :
 7      Foo(){}
 8       static  new_handler set_new_handler(new_handler p)  throw ();
 9       void *   operator   new (size_t size);
10  private :
11       static  new_handler currentHandler;
12  };
13 
14  new_handler Foo::currentHandler  =   0 ;
15 
16  void *  Foo:: operator   new (size_t size)
17  {
18       throw  bad_alloc();
19  }
20 
21  new_handler Foo::set_new_handler(new_handler p)  throw ()
22  {
23       // new_handler oldHandler = currentHandler;
24       // currentHandler = p;
25      std::set_new_handler(p);
26       return  p;
27       // return oldHandler;
28  }
29 
30  void  outOfMem()
31  {
32      cout  <<   " out of memory "   <<  endl;
33  }
34 
35  int  main()
36  {
37      set_new_handler(outOfMem);
38      cout  <<   " Attempting to allocate 1 GB... " ;
39       char *  p  =   new   char  [ 1024 * 1024 * 1024 * 1024 * 1024 ];
40      cout  <<   " Ok\n " ;
41      delete[] p;
42      cin. get ();
43       return   0 ;
44  }

转载于:https://www.cnblogs.com/zhtf2014/archive/2011/04/09/2010691.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值