set_new_handler

#include <iostream> #include <new.h> using namespace std; int __cdecl newhandler(unsigned int ) { cout<<"the new_handler is called:"<<endl; throw bad_alloc(); return 0; } int main(int argc, char* argv[]) { ::_set_new_handler(newhandler); try { while(1) { new int[5000000]; cout<<"Allocating 5000000 ints"<<endl; } } catch (exception e) { cout<<e.what()<<"xxx"<<endl; } return 0; }

_set_new_handler在MSDN中的声明是
_PNH _set_new_handler( _PNH pNewHandler );

_set_new_handler在MSDN中的说明是:Transfer control to your error-handling mechanism if the new operator fails to allocate memory.翻译过来就是:如果new操作符分配内存失败,则转向_set_new_handler所指

误处理机制中去处理。

_set_new_handler具有一个参数:_PNH pNewHandler,_PNH的声明是:
typedef int (__cdecl * _PNH)( size_t );
说明pNewHandler是一个指向某个函数入口的指针,该函数返回一个整型值。如果返回0,则表示告诉new操作符不要尝试去分配内存,返回非0,则表示告诉new操作符继续尝试分配内存。

你可能感兴趣的:(set_new_handler)