Why destructor is not called on exception?(为什么异常时不调用析构函数?)
问题描述
我希望 A::~A()
在这个程序中被调用,但它不是:
#include <iostream>结构 A {~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.
这篇关于为什么异常时不调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么异常时不调用析构函数?
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- GDB 不显示函数名 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04