我希望 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/