gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:06:54 26 4
gpt4 key购买 nike

#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;
}
}

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

最佳答案

测试析构函数在 main 退出后调用。

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

正在测试

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

Static(静态存储持续时间对象)在main退出后按照创建的相反顺序销毁。

关于c++ - 抛出异常时是删除静态对象,还是只删除本地对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com