Search code examples
c++exceptiondestructorraiistack-unwinding

Is it safe to use RAII while stack unwinding?


class AutoSomething
{
public:
    AutoSomething(Object& ob)
        : object_(object)
    {}

    ~AutoSomething()
    {
        object_.some_callback();
    }

private:
    Object& object_;
};

.........

void Object::some_function()
{
    AutoSomething some(*this);

    some_function_which_may_throw_exception();
}

The question is - will the state of Object be OK when the destructor of AutoSomething will be called?


Solution

  • Stack unwinding is the situtation for which RAII was invented in the first place. So it is most certainly the proper tool for that.

    In your particular case, there is no reason why the code should behave incorrectly. The only problem could arise if some_callback relies on an internal invariant of Object which is not maintained when some_function_which_may_throw_exception actually throws, but that would a problem of the particular code and has nothing to do with C++ itself.