演示C++在构造函数中抛出异常时,不调用析构函数,导致资源不能释放的一种解决方法。
namespace TEST
{
void exception()
{
class A
{
public:
A()
{
cout<<"I am in A."<<endl;
try
{
m_pBuf = new char[100];
throw std::runtime_error("test");
}
catch(...)
{
cleanup();
}
}
~A()
{
cout<<"I will out A."<<endl;
}
private:
char* m_pBuf;
void cleanup()
{
cout<<"i am in cleanup."<<endl;
}
};
A a;
}
}
int main()
{
try
{
TEST::exception();
}
catch(exception& error)
{
cout<<"info is "<< error.what()<<endl;
}
catch (...)
{
cout<<"issue a exception."<<endl;
}
getchar();
return 1;
}