安全地从dtor抛出异常

时间:2019-07-06 18:20:58

标签: c++ c++11

在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=1部分,我想得到throw 1;,否则,请获取ex=2

目前,我得到terminate called after throwing an instance of 'int' 尽管进行了if检查,但我认为应该在已经激活异常的情况下阻止第二次抛出。

1 个答案:

答案 0 :(得分:3)

您正在寻找std::uncaught_exceptions

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