ScopeGuard and exceptions
The ScopeGuard pattern is designed to correctly run various cleanup and rollback operations automatically upon exiting a scope, no matter what caused the exit—normal completion by reaching the end of the scope, an early return, or an exception. This makes writing error-safe code in general, and exception-safe code in particular, much easier; as long as we queued up the right guards after every action, the correct cleanup and error handling will automatically happen. That is, of course, assuming that ScopeGuard itself is functioning correctly in the presence of exceptions. We are going to learn how to make sure it does and how to use it to make the rest of the code error-safe.
What must not throw an exception
We have already seen that the commit()
function that is used to commit an action and disarm the rollback guard must never throw an exception. Fortunately, that is easy to guarantee since all this function does is set a flag. But what happens...