在C++中,重载delete operator的一个非常重要的应用是:当用户重定义了一个new operator,并分配了资源。若在创建时发生异常,则编辑器会自动调用delete operator进行处理。见如下代码示例:
#include <iostream>
class C {
public:
class Bad_create {};
C()
{
std::cout << "C::C() is called !~\n";
}
C(int ) throw ( Bad_create )
{
std::cout << "C::C( int ) is called.!~\n";
throw Bad_create();
}
void operator delete( void * p)
{
std::cout << "C::operator delete( void *) is called !~\n";
}
};
void main(char * args[], int argc)
{
try{
C *c = new C( 0 );
}
catch(C::Bad_create &e)
{
}
}
运行截图
若在创建时发生异常,则系统会自动调用delete operator进行用户自定义的资源释放操作。