抛出异常时是删除静态对象,还是只删除本地对象
Are static objects deleted when an exception is thrown, or just local objects?
#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
对象不会被销毁,因为它们应该持续整个程序。如果它们被清除,如果对这些对象的引用在程序中传递,可能会导致问题。
希望这能有所帮助!
相关文章:
- 迭代时从向量和内存中删除对象
- C++从对象自己的类中删除对象
- 如何通过对象的类属性删除对象,并返回其对象值?
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 从列表C++中删除对象
- c++ 循环访问对象列表并删除对象
- 从对象本身的容器中删除对象
- 从尝试引用已删除函数的矢量 C++ 中删除对象
- 如何通过指向元组的共享指针删除对象
- 防止通过接口删除对象
- 在 c++ 中从内存中删除对象
- 当对象被删除时,复制被删除对象的对象如何
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 从内存中删除对象
- 通过C++中的删除方法自行删除对象
- C++ - 析构函数只是释放内存还是实际删除对象
- 如何通过存储在 std::list 中的指针删除对象?
- 如何通过对象参数从指针矢量中删除对象和指针
- 我可以删除对象的右值版本的函数吗?
- 使用对象的索引从矢量中删除对象