原型:_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(); }