【问题标题】:why destructor is not called in this class为什么在这个类中不调用析构函数
【发布时间】: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&lt;&lt;1/i 以强制执行。

标签: c++ exception destructor


【解决方案1】:

除以零也不例外!无法捕获它,因为它是向操作系统发出的硬件信号以中断您的程序。

在这里阅读更多:

C++ : Catch a divide by zero error

为了抛出一个随机异常,你可以这样做

throw std::runtime_error("Oh no!");

但请确保在调用代码中捕获抛出的异常:

try {
   codeThatThrowsException();
} catch(const std::runtime_error& e) {
   std::cout << "An exception was thrown: " << e.what() << std::endl;
}

【讨论】:

  • 反正不在 C++ 中。不要一概而论。
  • @Blindy:它被标记为 C++
  • 如何生成异常来检查析构函数是否被调用?
  • @mans 你可以抛出一个异常。但是为了正确展开堆栈,无论如何您都需要在抛出异常的代码周围设置一个 try 块。
猜你喜欢
  • 1970-01-01
  • 2011-12-13
  • 2022-07-01
  • 2015-08-21
  • 1970-01-01
  • 2017-05-18
  • 2021-08-04
  • 2015-07-18
相关资源
最近更新 更多