#include <iostream> #include <new> using namespace std; class CSaveCurHandler //用于管理new_handler,保存原始的new_handler,在new成功结束后还原. { private: new_handler cur; public: CSaveCurHandler(new_handler nh) :cur(nh){} ~CSaveCurHandler() { set_new_handler(cur); } }; template<class T> class CWidget { private: static new_handler cur_handler; public: static void set_handler(new_handler nh) { cur_handler = nh; } static void *operator new(size_t size) throw(std::bad_alloc) { CSaveCurHandler sch(set_new_handler(cur_handler)); //将原始的保存至CSaveCurHandler对象中 return ::operator new(size); //,调用系统原始的new,返回后自动还原new_handler } }; void outMen() { cout << "内存不够"; } template<class T> new_handler CWidget<T>::cur_handler = outMen; class MY : public CWidget<MY> { private: char buf[1025 * 1024 * 1024]; }; int main() { MY::set_handler(outMen); while (1) MY *p = new MY; cin.get(); return 0; }