samedi 6 juillet 2019

Safely throwing an exception from a dtor

In C++>=11, is it possible to safely throw an exception from a destructor, i.e., only throw it if no exception is already active?

I have tried:

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

without success. Am I using the std::current_exception function wrong?

Aucun commentaire:

Enregistrer un commentaire