条款7:预先准备好内存不够的情况
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 <iostream> #include <new> using namespace std; /* #define NEW(PTR, TYPE) \ try {(PTR) = new TYPE; } \ catch (std::bad_alloc&) { assert(0); } */ //new异常处理模版类 template <class T> 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 <class T> new_handler NewHandlerSupport<T>::set_new_handler(new_handler handler) { new_handler old_handler = current_handler; current_handler = handler; return old_handler; } //重写new template<class T> void* NewHandlerSupport<T>::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<class T> new_handler NewHandlerSupport<T>::current_handler; //具体类继承模版实例 class Example : public NewHandlerSupport<Example> { public: //... private: //... }; int main() { Example* e = new Example; return 0; }
4. 如果想让new分配失败不抛出异常而是返回0,可以像下面这样
int* i = new (nothrow) int;
不积跬步无以至千里,不积小流无以成江河。