【发布时间】:2014-04-22 20:48:38
【问题描述】:
我在 test.h 中有一个简单的类,如下所示
class test
{
test()
{
std::cout<<"constructor called"<<std::endl;
}
static test m_test;
~test()
{
std::cout<<"I am here"<<std::endl;
}
};
静态成员在 test.cpp 中定义为:
test test::m_test;
主要什么都没有:
main()
{
}
我可以在输出中看到:
constructor called
I am here
这很好。现在我添加了一些生成异常的代码,如下所示:
main()
{
for(int i=-1; i<1; i++)
{
i=1/i; // this line generate an exception and close the application.
}
}
在这种情况下,不调用析构函数。我只能看到构造函数被调用。
为什么会这样?
如何确保如果抛出期望并且应用程序崩溃,则调用析构函数?假设我只能更改我的测试类而不是主应用程序。
【问题讨论】:
-
析构函数不是只在实例化的类上调用吗?
-
如果你的应用程序崩溃了,是什么让你认为像析构函数这样的函数会在崩溃中幸存下来?
-
在ideone上调用:ideone.com/5a8e20
-
依赖于平台,在 win32 上它将是一个 SEH 异常,并且会在除以零时简单地崩溃和烧毁
-
@Nawaz 那是因为 ideone 对其进行了优化编译,删除了无用的
i=1/i行。将其更改为std::cout<<1/i以强制执行。
标签: c++ exception destructor