欢迎光临散文网 会员登陆 & 注册

C++构造函数中抛出异常,不执行析构函数的例子

2023-04-09 06:03 作者:淡定的茶  | 我要投稿

演示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;
}


C++构造函数中抛出异常,不执行析构函数的例子的评论 (共 条)

分享到微博请遵守国家法律