内存分配失败的处理

看到effective c++中内存分配的处理,编写代码便于以后的理解:

1. 基本版:

 

msdn上这么解释:

Call the C++ _set_new_handler function to specify an exception-handling function that is to gain control if the new operator fails to allocate memory. If new fails, the run-time system automatically calls the exception-handling function that was passed as an argument to _set_new_handler. _PNH, defined in NEW.H, is a pointer to a function that returns type int and takes an argument of type size_t. Use size_t to specify the amount of space to be allocated.

_set_new_handler is essentially a garbage-collection scheme. The run-time system retries allocation each time your function returns a nonzero value and fails if your function returns 0.

 

2. effective c++上提供的一条有效的建议是提供一个类作为基类,这样子类

等出现内存分配失败时,均可以用到,也可以写为模板类,代码如下:

 

 

为了让内存尽快耗完,我在class内部定义一个大block的内存块,这样就能在

main中定义到第二个变量时变出现了内存分配失败的情形,其实在NonMemory这样的函数中,

应该尽量做到垃圾内存回收,并且返回1,这样的话,会让分配失败后,继续调用分配内存,这样才是

我们编程人员想要的结果。以上纯为effective c++中“预先准备内存不足”这一章节的个人理解描述。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值