class Widget
{
public:
Widget() {
cout<<"~Widget()"<<endl;
}
~Widget() {
cout<<"~Widget()"<<endl;
}
void* operator new(size_t sz) throw(bad_alloc) {
cout<<"operator new"<<endl;
throw bad_alloc();
}
void operator delete(void *v) {
cout<<"operator delete"<<endl;
}
};
int main()
{
Widget* w = 0;
try {
w = new Widget();
}
catch(bad_alloc) {
cout<<"Out of Memory"<<endl;
}
delete w;
getch();
return 1;
}
在此代码中,当析构函数存在时,delete w
不会调用重载运算符。delete
如果省略析构函数,delete
则调用重载的。为什么会这样?
写入 ~Widget() 时的输出
运算符 new
内存不足
没有写入~Widget() 时的输出
运算符 new
内存不足
运算符 delete