c++ - 为什么异常时不调用析构函数?

标签 c++ exception visual-c++ destructor stack-unwinding

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

#include <iostream>

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

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

int main() { f(); }

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

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

然后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++ 的调试跟踪似乎证实了这一点。

根据draft standard第 15.3 节第 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.

关于c++ - 为什么异常时不调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/222175/

相关文章:

c++ - 由于换行字符不同的结果

c++ - 你能从一个单独的程序中删除动态分配的内存吗?

c# - 如何显示标准 SharePoint "Access Denied"消息

c++ - 在不调用默认构造函数的情况下声明对象

*不*初始化其成员的C++ vector ?

c++ - 在析构函数中正确使用 std::uncaught_exception

heroku - 在 Heroku 日志中显示 Python 异常错误

c++ - 如何释放字符串未使用的容量

c - 正在链接...链接: fatal error LNK1181: cannot open input file 'libgsl.a'

c++ - 使用键盘 Hook 时无法动态退出循环