std::set_new_handler 用於若是 new 失敗就調用此函數;函數
int * gmem = 0; void outofmem() { std::cerr << "mem alloc failed" << endl; Sleep(500); //稍微睡一下,否則中止調式按鈕都沒反映啦 } int main(int argc, char *argv[]) { enum { Chunk = 1024 * 1024 * 8 }; std::set_new_handler(outofmem); gmem = new int[100000000000 * Chunk]; //一旦失敗調用outofmem. 不斷的調用 return 0; }
只要new 失敗則一直調用此函數 , 直到有足夠的內存爲止, 意圖在讓你去釋放一些內存;code
set_new_handler(0); 用來還原內存
若是有需求通常寫一個父類去實現:class
class MemHandler{ //用於還原handler public: MemHandler(std::new_handler handler) :handler(handler){} ~MemHandler(){ std::set_new_handler(handler);} private: MemHandler(const MemHandler &) ; MemHandler & operator = (const MemHandler &); std::new_handler handler; }; //也能夠把此類寫成 template <typename T> class NewHandlerBaseClass{ public: static std::new_handler setNewHandler(std::new_handler newhandler) throw() { std::new_handler old_hanlder = m_handler; m_handler = newhandler; return old_hanlder; } //重載一個 static void * operator new (std::size_t size) throw (std::bad_alloc){ MemHandler memhandler(std::set_new_handler(m_handler)); //設置handler return ::operator new(size); //仍是調用原來的new } private: static std::new_handler m_handler; }; //若是上面的類是模版的話 . 每一個類都有一個獨立的static m_handler; class XClass : public NewHandlerBaseClass<XClass> { .... };