为什么析构函数不会被异常处理

为什么析构函数不会被异常处理

本文介绍了为什么析构函数不会被异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在此程序中调用 A ::〜A(),但不是:

  #include< iostream> 

struct A {
〜A(){std :: cout<<< 〜A()<的std :: ENDL; }
};

void f(){
A a;
throwspam;
}

int main(){f();

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



int $ {code> int main()try {f(); catch(...){throw;

然后 A ::〜A()



我正在使用Microsoft(R)32位C / C ++优化编译器版本14.00.50727.762 for 80x86从Visual Studio 2005。命令行是 cl / EHa my.cpp



编译器是否像往常一样?标准说这个问题是什么?

解决方案

析构函数未被调用,因为未处理异常的terminate()被调用堆栈得到解开。



C ++规范说明的具体细节不在我的知识之外,但使用gdb和g ++的调试跟踪似乎承担了这一点。 / p>

根据部分15.3项目符号9:

 
9如果程序中没有找到匹配的处理程序,则函数终止()
(_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.

这篇关于为什么析构函数不会被异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:40