set_new_handler用法

原型:_PNH _set_new_handler( _PNH pNewHandler );

 

MSDN解释:Transfer control to your error-handling mechanism if the new operator fails to allocate memory.

如果new操作符分配内存失败,则转向_set_new_handler所指定的错误处理机制中去处理。

 

实例:In this example, when the allocation fails, control is transferred to MyNewHandler.

The argument passed to MyNewHandler is the number of bytes requested.

The value returned from MyNewHandler is a flag indicating whether allocation should be retried:

a nonzero value indicates that allocation should be retried, and a zero value indicates that allocation has failed.

 

当内存分配失败的时候,调用MyNewHandler. 传递给MyNewHandler的参数是需要的bytes字节数.

而MyNewHandler得返回值代表内存分配是否需要被重新调用。

如果返回0,则表示告诉new操作符分配内存失败;

返回非0,则表示告诉new操作符继续尝试分配内存。

 

#include <stdio.h>
#include <new.h>
#define BIG_NUMBER 0x1fffffff

int coalesced = 0;

int CoalesceHeap()
{
   coalesced = 1;  // Flag RecurseAlloc to stop 
   // do some work to free memory
   return 0; //表明分配内存失败,程序退出,如果return 1的程序不断的再重新分配内存
}
// Define a function to be called if new fails to allocate memory.
int MyNewHandler( size_t size )
{
   printf("Allocation failed. Coalescing heap./n");

   // Call a function to recover some heap space.
   return CoalesceHeap();
}

int RecurseAlloc() {
   int *pi = new int[BIG_NUMBER];
   if (!coalesced)
      RecurseAlloc();
   return 0;
}

int main()
{
   // Set the failure handler for new to be MyNewHandler.
   _set_new_handler( MyNewHandler );
   RecurseAlloc();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值