Why destructor is not called on exception?(为什么在异常时不调用析构函数?)
问题描述
我希望在这个程序中调用 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.
这篇关于为什么在异常时不调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在异常时不调用析构函数?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01