停止执行而不跳过析构函数
是否可以终止软件执行而不跳过对析构函数的调用?例如,在下面的代码中,由于 exit(1)
语句,test
的析构函数永远不会被调用。
#include <iostream>
#include <cstdlib>
using namespace std;
class A{
public:
A(){cout << "Constructed.\n";}
~A(){cout << "Destroyed.\n";}
};
void func()
{
//Assuming something went wrong:
exit(1);
}
int main(int argc, char *argv[])
{
A test;
func();
return 0;
}
我需要的是一种结束程序的方法(从 func()
内部),在终止之前调用所有必要的析构函数。到目前为止,我一直通过 func() 返回值来处理这个问题,如下所示:
bool func()
{
//Assuming something went wrong:
return false;
}
int main(int argc, char *argv[])
{
A test;
if( !func() )return 1;
return 0;
}
此方法的问题是,一旦需要应用它,管理起来很快就会变得非常烦人(并且代码膨胀)一系列嵌套函数。
有没有一种方法可以使用与第一个示例类似的语法(无论您身在何处,都调用 exit(1)
)来实现与第二个示例(正确的析构函数调用)相同的结果?
Is it possible to terminate software execution without skipping calls to destructors? For instance, in the code below, the destructor for test
will never be called because of the exit(1)
statement.
#include <iostream>
#include <cstdlib>
using namespace std;
class A{
public:
A(){cout << "Constructed.\n";}
~A(){cout << "Destroyed.\n";}
};
void func()
{
//Assuming something went wrong:
exit(1);
}
int main(int argc, char *argv[])
{
A test;
func();
return 0;
}
What I need, is a way to end the program (from within func()
) that calls all necessary destructors before terminating. So far I've been handling this through func()
return value, as in:
bool func()
{
//Assuming something went wrong:
return false;
}
int main(int argc, char *argv[])
{
A test;
if( !func() )return 1;
return 0;
}
The problem with this method is that it quickly becomes very annoying (and code bloating) to manage once you need to apply it to a series of nested functions.
Is there a way of achieving the same results of the second example (proper destructor calls) with a syntax similar to the first example (call exit(1)
wherever you are)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
抛出异常,在
main
中捕获它并返回。这不依赖于任何其他东西来捕获您的异常而不重新抛出它。
Throw an exception, catch it in
main
and return.This relies on nothing else catching your exception without rethrowing it.
您可以依靠堆栈展开来实现此目的:当你想退出时,抛出异常并在
main()
中捕获它。You could rely on stack unwinding for this: when you want to exit, throw an exception and catch it in
main()
.有几种方法可以干净地做到这一点。
一种解决方案是使用atexit函数,该函数在程序终止时简单地调用给定的函数指针。
您必须从堆中分配所有对象,维护一些全局表,其中包含指向所有实例化类实例的指针,然后简单地遍历该表
删除
已注册函数中的每个实例。There are several ways to do this cleanly.
One solution is to use the
atexit
function, which simply calls the given function pointer when the program terminates.You would have to allocate all of your objects off the heap, maintain some global table with pointers to all instantiated class instances, and then simply iterate through the table
delete
ing each instance in the registered function.