首页 > 解决方案 > 从 dtor 安全地抛出异常

问题描述

在 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错误的功能?

我想知道ex=1throw 1;部分是否已启用,ex=2否则。

目前我得到了terminate called after throwing an instance of 'int' 尽管if检查,我认为应该阻止第二次抛出,而异常已经处于活动状态。

标签: c++c++11

解决方案


你正在寻找std::uncaught_exceptions.

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


推荐阅读