Ara*_*san 3 c++ exit-code exit c++11 c++14
如果满足某个条件,我希望我的C++代码停止运行并进行适当的对象清理; 在类的构造函数中.
class A {
public:
int somevar;
void fun() {
// something
}
};
class B {
public:
B() {
int possibility;
// some work
if (possibility == 1) {
// I want to end the program here
kill code;
}
}
};
int main() {
A a;
B b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何在此时终止我的代码进行适当的清理.众所周知,std::exit不执行任何类型的堆栈展开,堆栈上没有活动对象会调用其各自的析构函数来执行清理.所以std::exit不是一个好主意.
当构造函数失败时,您应该抛出异常.
B() {
if(somethingBadHappened)
{
throw myException();
}
}
Run Code Online (Sandbox Code Playgroud)
一定要捕获main()所有线程入口函数中的异常.
阅读更多内容从构造函数中抛出异常.阅读有关堆栈展开的信息如何处理失败的析构函数.
| 归档时间: |
|
| 查看次数: |
825 次 |
| 最近记录: |