gpt4 book ai didi

c++ - 为什么不能在 dtor 中使用 uncaught_exception?

转载 作者:行者123 更新时间:2023-11-30 03:08:46 27 4
gpt4 key购买 nike

Herb Sutter 在他的文章中 http://www.gotw.ca/gotw/047.htm指出我们不能在析构函数中使用uncaught_exception,

//  Why the wrong solution is wrong
//
U::~U() {
try {
T t;
// do work
} catch( ... ) {
// clean up
}
}

如果 U 对象在异常传播期间由于堆栈展开而被销毁,T::~T 将无法使用“可能抛出的代码”路径,即使它可以安全地使用。

但是我写了一个测试程序,而T::~T其实并没有使用“可能抛出的代码”

#include <exception>
#include <iostream>
using namespace std;

class T {
public:
~T() {
if( !std::uncaught_exception() )
{
cout<<"can throw"<<endl;
throw 1;
} else
{
cout<<"cannot throw"<<endl;
}
}


};

struct U
{
~U() {
try
{
T t;
}
catch( ... )
{
}
}
};

void f()
{
U u;
throw 2;
}

int main()
{
try
{
f();
}
catch(...)
{}
}

输出是:不能扔

我错过了什么吗?

谢谢

最佳答案

这正是他的意思:“will fail to throw”的意思是“不会抛出,因为它会认为在当前上下文中抛出是不安全的”(not“会崩溃”;在这里失败意味着不会发生)。因为析构函数作为异常引起的堆栈展开的一部分被调用 std::uncaught_exception() 返回 true,而 T::~T() 没有使用可能抛出的代码(用他的话说:T::~T 将无法使用“可能抛出的代码”路径,即使它安全地可以)因为它认为它不应该扔。关键是因为 T 包裹在 try{}catch(...){} block 中,它是可以安全抛出的,即使存在未决的异常。

关于c++ - 为什么不能在 dtor 中使用 uncaught_exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4624132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com