gpt4 book ai didi

c++ - 从 dtor 安全地抛出异常

转载 作者:行者123 更新时间:2023-11-30 02:14:58 26 4
gpt4 key购买 nike

在 C++ 中>=11,是否可以安全地从析构函数中抛出异常,即仅在没有异常处于事件状态时才抛出异常?

我试过:

#include <exception>
#include <stdexcept>
#include <stdio.h>
struct foo{
foo();
~foo() noexcept(false);
};
foo::foo() { }
foo::~foo() noexcept(false)
{
if (nullptr==std::current_exception())
throw 2;
}
int main()
{
try{
struct foo f;
#if 1
throw 1;
#endif
}catch(int X){
printf("ex=%d\n", X);
}
}

没有成功。我是不是用错了 std::current_exception 函数?

如果 throw 1; 部分启用,我想得到 ex=1,否则 ex=2

目前我得到 在抛出“int”实例后调用终止尽管 if 检查,但我相信,当异常已经激活时,应该阻止第二次抛出。

最佳答案

您正在寻找 std::uncaught_exceptions .

std::current_exception 返回指向异常的指针当前正在处理(即在 catch block 中)。

关于c++ - 从 dtor 安全地抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916616/

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