ScopeGuard dismiss

574 Views Asked by At

My code needs scope guards, however do I have to manually Dismiss() all the scope guards on exit from a function normally? i.e.

void Deleter(MyClass* obj)
{
    delete obj;
}

MyClass* Func()
{
    MyClass* obj = new MyClass();
    ScopeGuard sg1 = MakeObjGuard(Deleter, obj);

    //More objects created. And more scope guards.

    sg1.Dismiss();
    //...Same for other guards
    return obj;
}
2

There are 2 best solutions below

1
On

Given this implementation of ScopeGuard, then the answer is yes. The object deletion will happen in the destructor of the ScopeGuard, unless you disable it by calling the Dismiss method.

0
On

You have to dismiss the guards for the objects you want to stay alive after the function. Otherwise they will each delete the object they are guarding.