为什么在这个类中没有调用析构函数

why destructor is not called in this class

本文关键字:调用 析构函数 为什么      更新时间:2023-10-16

我有一个简单的类,在test.h

class test
{
        test()
        {
            std::cout<<"constructor called"<<std::endl;
        }
        static test m_test;
        ~test()
        {
            std::cout<<"I am here"<<std::endl;
        }
};

, static成员在test.cpp中定义为:

test test::m_test;

main没有任何内容:

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.
     }
}
在这种情况下,不调用析构函数。我只能看到构造函数被调用了。

为什么会这样?

如何确保在抛出期望并且应用程序崩溃时调用析构函数?假设我只能更改我的测试类而不能更改主应用程序

除零也不例外!这是不可能捕捉到的,因为它是一个硬件信号,操作系统中断您的程序。

阅读更多:

c++:捕获除零错误

要抛出随机异常,只需执行

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

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

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