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

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.

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

本文标题为:为什么异常时不调用析构函数?

基础教程推荐