Search code examples
c++destructoruncaught-exceptionstack-unwinding

Is there any trick to detect if an object is created during execution of another destructor?


This is kind of a follow up on Why can't Alexandrescu use std::uncaught_exception() to implement SCOPE_FAIL in ScopeGuard11?

I would like to detect if someone is creating MyClass in the destructor of another class (or with an active destructor somewhere in the call stack).

class MyClass
{
public:
    MyClass(){
        assert(???what to put here????);
    }
}

void f(){
    MyClass m;    //whether this asserts should be context dependant
}

class OtherClass{
    ~OtherClass(){
        MyClass m; //this should assert
        f();       //this should too;
    }
}

int main()
{
    MyClass m;   //this should not assert
    f();         //this should also not assert
}

One attempt might be:

assert(!std::uncaught_exception());

but that would only work if the destructor is being invoked because of an exception, not if it is invoked because the object went out of scope.


Solution

  • you cannot detect this and you don't want to. it's not your class's business. if someone will call you from noexcept destructor, he will catch exceptions