3

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

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

“在堆栈展开期间,所有这些堆栈帧中的所有本地对象都被破坏了。如果其中一个析构函数抛出异常(比如它抛出一个 Bar 对象),C++ 运行时系统处于无赢的境地:它是否应该忽略Bar and end up in the } 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() 函数。以下示例演示了这一点:”

4

1 回答 1

7

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

编辑:这是标准中的一个相关引用(强调添加)

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

于 2011-04-27T00:48:28.577 回答