为什么在异常时不调用析构函数?

时间:2023-04-14
本文介绍了为什么在异常时不调用析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我希望在这个程序中调用 A::~A(),但它不是:

#include 结构体{~A() { std::cout <<"~A()" <<std::endl;}};无效 f() {一个;扔垃圾邮件";}int main() { f();}

但是,如果我将最后一行更改为

int main() try { f();} 捕捉(...){ 扔;}

然后 A::~A() 调用.

我正在使用 Visual Studio 2005 的Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86"进行编译.命令行是 cl/EHa my.cpp.

编译器正常吗?标准在这件事上是怎么说的?

解决方案

未调用析构函数,因为在堆栈展开之前调用了未处理异常的 terminate().

C++ 规范所说的具体细节超出了我的知识范围,但 gdb 和 g++ 的调试跟踪似乎证实了这一点.

根据草案标准第 15.3 节第 9 点:

<前>9 如果在程序中找不到匹配的处理程序,则函数 terminate()(_except.terminate_) 被调用.堆栈是否展开在调用 terminate() 之前是实现定义的.

I expected A::~A() to be called in this program, but it isn't:

#include <iostream>

struct A {
  ~A() { std::cout << "~A()" << std::endl; }
};

void f() {
  A a;
  throw "spam";
}

int main() { f(); }

However, if I change last line to

int main() try { f(); } catch (...) { throw; }

then A::~A() is called.

I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is cl /EHa my.cpp.

Is compiler right as usual? What does standard say on this matter?

解决方案

The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.

The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.

According to the draft standard section 15.3 bullet 9:

9 If no matching handler is found in a program, the function terminate()
  (_except.terminate_)  is  called.  Whether or not the stack is unwound
  before calling terminate() is implementation-defined.

这篇关于为什么在异常时不调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:当构造函数抛出异常时会运行哪些析构函数? 下一篇:异常后重置 Cuda 上下文

相关文章