- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这不是关于从析构函数中抛出异常是否安全的问题。
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9状态:
“在堆栈展开期间,所有这些堆栈帧中的所有本地对象都被破坏。如果其中一个析构函数抛出异常(比如抛出一个 Bar 对象),C++ 运行时系统将处于双赢局面:应该它忽略 Bar 并最终进入 } catch (Foo e) { 它最初前往的地方?它应该忽略 Foo 并寻找 } catch (Bar e) { 处理程序吗?没有好的答案 - 任何一个选择都会丢失信息”
IE:如果在堆栈展开期间抛出另一个异常,则运行时系统处于双赢局面,因为要“查找”的捕获处理程序不明确。
当在堆栈展开过程中抛出的异常在 try/catch block 中时,上面是否存在“异常”?在这种情况下没有歧义:
#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++ 标准部分。
“如果在堆栈展开期间析构函数抛出异常并且未处理该异常,则调用 terminate() 函数。以下示例演示了这一点:”
最佳答案
您的组件析构函数是安全的。您引用的规则仅适用于从析构函数中抛出异常的情况(即,抛出给析构函数的调用者。)
编辑:这是来自 standard 的一段相关引述。 (强调)
Note: If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1).
关于C++ 从析构函数中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5798107/
我是一名优秀的程序员,十分优秀!