1. operator new在无法完成内存分配请求时会抛出异常(在以前或者某些特定情况(声明nothrow)下new会返回0)
2. 使用C语言的宏定义处理会是这样
#define NEW(PTR, TYPE) \ try {(PTR) = new TYPE; } \ catch (std::bad_alloc&) { assert(0); }
3. 用C++的异常处理机制,处理方法是这样
#include#include using namespace std;/*#define NEW(PTR, TYPE) \ try {(PTR) = new TYPE; } \ catch (std::bad_alloc&) { assert(0); }*///new异常处理模版类template class NewHandlerSupport{public: static new_handler set_new_handler(new_handler handler); static void* operator new(size_t size);private: static new_handler current_handler;};//设置异常处理函数template new_handler NewHandlerSupport ::set_new_handler(new_handler handler){ new_handler old_handler = current_handler; current_handler = handler; return old_handler;}//重写newtemplate void* NewHandlerSupport ::operator new(size_t size){ void* memory = NULL; new_handler old_handler = ::set_new_handler(current_handler); try { memory = ::operator new(size); } catch (std::bad_alloc&) { set_new_handler(old_handler); throw; } set_new_handler(old_handler); return memory;}//初始化静态数据template new_handler NewHandlerSupport ::current_handler;//具体类继承模版实例class Example : public NewHandlerSupport {public: //...private: //...};int main(){ Example* e = new Example; return 0;}
4. 如果想让new分配失败不抛出异常而是返回0,可以像下面这样
int* i = new (nothrow) int;