【问题标题】:C++ throwing an exception from a destructorC++ 从析构函数中抛出异常
【发布时间】:2022-01-16 11:58:41
【问题描述】:

这不是关于从析构函数中抛出异常是否安全的问题。

http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9 状态:

“在堆栈展开期间,所有这些堆栈帧中的所有本地对象都被破坏。如果这些析构函数中的一个抛出异常(比如它抛出 Bar 对象),C++ 运行时系统处于无赢状态:应该它忽略了 Bar 并最终在 } catch (Foo e) { 它原来的方向?它应该忽略 Foo 并寻找一个 } catch (Bar e) { 处理程序吗?没有好的答案——任何一个选择都会丢失信息。”

IE:如果在堆栈展开期间抛出另一个异常,则运行时系统处于无赢状态,因为要“查找”的 catch 处理程序不明确。

当堆栈展开期间引发的异常位于 try/catch 块中时,是否存在上述“异常”?在这种情况下没有歧义:

#include <iostream>
using namespace std;

class Component
{
public:
    ~Component()
    {
        cout << "In component destructor" << endl;
        try
        {
            throw 1;
        }
        catch (...)
        {
            cout << "Caught exception in component destructor" << endl;
        }
    }

};

class Container
{
public:
    ~Container()
    {
        cout << "In container destructor" << endl;
        Component component;
    }
}
    ;

int main()
{
    try
    {
        Container cont;
        throw 'a';
    }
    catch (...)
    {
        cout << "Caught main exception ok" << endl;
    }
return 0;
}

以下暗示,但我想知道是否有人知道相关的 C++ 标准部分。

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr155.htm

“如果在堆栈展开期间析构函数抛出异常并且该异常未被处理,则调用 terminate() 函数。以下示例演示了这一点:”

【问题讨论】:

    标签: c++ exception-handling stack-unwinding


    【解决方案1】:

    您的组件析构函数是安全的。您引用的规则仅适用于从析构函数抛出异常(即,向析构函数的调用者抛出异常)。

    编辑:这是来自standard 的一段相关引述(已添加重点)

    注意:如果在期间调用了析构函数 堆栈展开退出 异常,调用 std::terminate (15.5.1)。

    【讨论】:

      猜你喜欢
      • 2013-04-03
      • 2015-08-26
      • 2019-03-11
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多