抛出异常时是删除静态对象,还是只删除本地对象

Are static objects deleted when an exception is thrown, or just local objects?

本文关键字:删除 对象 静态 抛出异常      更新时间:2023-10-16
#include <iostream>
#include <exception>
using std::cout;
using std::endl;
class test
{
 public:
    test()
    {
        cout<<"constructor called"<<endl;
    }
    ~test()
    {
        cout<<"destructor called"<<endl;
    }
    void fun(int x)
    {
       throw x;
    }
};
int main()
{
    try
    {
        static test k;          
        k.fun(3);
    }
    catch(int k)
    {
        cout<<"exception handler"<<endl;
    }
}

当抛出异常时,在堆栈展开过程中,我认为只有本地对象被销毁,而不是静态或堆对象。如果这是真的,我不确定为什么要调用类(测试(析构函数?谢谢

在主出口后调用测试析构函数。

    catch(int k)
    {
        cout<<"exception handler"<<endl;
    }
    // Added this line
    std::cout << "Main Exitingn";
}

正在测试

> g++ test.cpp
> ./a.out
constructor called
exception handler
Main Exiting
destructor called

静态(静态存储持续时间对象(在主出口后按与创建相反的顺序销毁。

因为程序正在退出,所以调用析构函数。只有自动存储持续时间的对象(绝对不是堆栈对象或堆对象(才会被销毁。

运行此代码时,我会得到输出

constructor called
exception handler
destructor called

这很有道理。首先调用静态test对象的构造函数。当抛出异常时,它会被异常处理程序捕获并打印消息。最后,当程序终止时,会调用静态test对象的析构函数。

异常只会导致具有自动持续时间的变量(即局部变量(的生存期结束,假设异常实际上是在某个地方捕获的。异常不会破坏具有动态持续时间的对象(即用new分配的对象(,但如果在动态分配对象的构造函数中发生异常,则内存将被回收,因为否则就无法收回内存。类似地,static对象不会被销毁,因为它们应该持续整个程序。如果它们被清除,如果对这些对象的引用在程序中传递,可能会导致问题。

希望这能有所帮助!