operator new and delete
Effective C++的笔记
1 #include <tr1/memory> 2 #include <iostream> 3 4 class NewHandlerHolder { 5 public: 6 explicit NewHandlerHolder(std::new_handler nh) 7 :handler(nh){ } 8 ~NewHandlerHolder() { std::set_new_handler(handler); } 9 private: 10 std::new_handler handler; 11 NewHandlerHolder(const NewHandlerHolder&); 12 NewHandlerHolder & operator=(const NewHandlerHolder&); 13 }; 14 15 template <typename T> 16 class NewHandlerSupport { 17 public: 18 static std::new_handler set_new_handler(std::new_handler p) throw(); 19 static void *operator new(std::size_t size) throw(std::bad_alloc); 20 static void *operator new(std::size_t size, std::nothrow_t &) throw(); 21 22 private: 23 static std::new_handler currentHandler; 24 }; 25 26 template <typename T> 27 std::new_handler NewHandlerSupport<T>::currentHandler = NULL; 28 29 template <typename T> 30 std::new_handler 31 NewHandlerSupport<T>::set_new_handler(std::new_handler p) throw() 32 { 33 //throw()指出,该函数不允许抛出异常,否则属于严重错误 34 std::new_handler oldHandler = currentHandler; 35 currentHandler = p; 36 return oldHandler; 37 } 38 39 template <typename T> 40 void * 41 NewHandlerSupport<T>::operator new(std::size_t size, std::nothrow_t &nt) throw() 42 { 43 NewHandlerHolder h(std::set_new_handler(currentHandler)); 44 return ::operator new(size, nt); 45 } 46 47 template <typename T> 48 void * 49 NewHandlerSupport<T>::operator new(std::size_t size) throw(std::bad_alloc) 50 { 51 NewHandlerHolder h(std::set_new_handler(currentHandler)); 52 53 return ::operator new(size); 54 } 55 56 class Widget : public NewHandlerSupport<Widget>{ 57 public: 58 Widget(){ } 59 ~Widget(){ std::cout << "Widget Destructor Enter" << std::endl; } 60 }; 61 62 int main(void) 63 { 64 std::cout << "Hello World!" << std::endl; 65 66 Widget::set_new_handler(NULL); 67 68 std::tr1::shared_ptr<Widget> pW(new Widget); 69 70 Widget *pw2 = ::new (std::nothrow) Widget; 71 if(pw2) 72 delete pw2; 73 74 return 0; 75 }