ScopeGuard dismiss

566 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 answers

1
BЈовић 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
Bo Persson 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.