class X
{ public:
static new_handler set_new_handler(new_handler p);
static void* operator new(size_t siz);
private:
static new_handler currentHandler;
};
new_handler X::currentHandler;//初始化为0
new_handler X::set_new_handler(new_handler p)
{ new_handler oldHandler = currentHandler;//保留当前new_handler
currentHandler = p;//再设置当前new_handler
return oldHandler;
}
void *X::operator new(size_t size) //调用一次特定处理方法,用毕恢复
{ newHandler globalHandler=std::set_new_handler(currentHandler);
//配置新new_handler 保存globalHandler
void *memory;
try{
memory = ::oprator new(size); //试分配内存
}
catch(std::bad_alloc&){
std::set_new_handler(globalHandler); //恢复原有处理方法
throw; //传播异常
}
std::set_new_handler(globalHandler): //恢复原有处理方法
return memory;
}
//应用
void nomoreMemory( );
X::set_new_handler(nomoreMemory);
X *px1 = new X; //如果内存分配失败,调用nomoreMemory( )
string *ps = new string; //如果内存分配失败,调用globalHandler
X:: set_new_handler(0);
X *px2 = new X; //如果内存分配失败,立即抛出异常
可以做一个混合风格基类允许 “设定class专属new_handler”
template