我想知道是否有一些方法可以在不引起segfault
或core dump
的情况下突然退出/终止程序。
我查看了 terminate()
和 exit()
以及 return 0
。它们似乎都不适用于我的项目。
if(this->board.isComplete())
{
Utils::logStream << " complete "<< endl;
this->board.display();
exit(0);
//std::terminate();
//abort();
//raise(SIGKILL);
return true;
}
最佳答案
exit()/abort()
和类似函数通常不是终止 C++ 程序的正确方法。正如您所注意到的,它们不运行 C++ 析构函数,使您的文件流保持打开状态。如果你真的必须使用 exit()
,然后用 atexit()
注册一个清理函数是个好主意,但是,我强烈建议您改用 C++ 异常。对于异常,会调用析构函数,如果在终止之前需要进行一些顶级清理,您始终可以在 main()
上捕获异常,进行清理,然后正常返回并返回错误代码.这也可以防止代码转储。
int main()
{
try
{
// Call methods that might fail and cannot recover.
// Throw an exception if the error is fatal.
do_stuff();
}
catch(...)
{
// Return some error code to indicate the
// program didn't terminated as it should have.
return -1;
}
// And this would be a normal/successful return.
return 0;
}
关于c++ - 在没有 coredump 或 Segmentation Faults 的情况下退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987847/