如果满足特定条件,我希望我的 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;
}
我怎样才能在那个时候终止我的代码进行适当的清理。据了解,std::exit
不执行任何类型的堆栈展开,并且堆栈上没有事件对象将调用其各自的析构函数来执行清理。所以std::exit
这不是一个好主意。
最佳答案
当构造函数失败时,你应该抛出异常,如下所示:
B() {
if(somethingBadHappened)
{
throw myException();
}
}
一定要在 main()
和所有线程入口函数中捕获异常。
阅读更多 Throwing exceptions from constructors .在 How can I handle a destructor that fails 中阅读有关堆栈展开的信息.
关于c++ - 如何直接从构造函数结束 C++ 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46515100/