The ScopeGuard pattern
In this section, we learn how to write the on-exit action RAII classes such as the ones we implemented in the previous section, but without all the boilerplate code. This can be done in C++03 but is much improved in C++14, and again in C++17.
ScopeGuard basics
Let’s start with the more difficult problem—how to implement a generic rollback class, a generic version of StorageGuard
from the last section. The only difference between that and the cleanup class is that the cleanup is always active, but the rollback is canceled after the action is committed. If we have the conditional rollback version, we can always take out the condition check, and we get the cleanup version, so let’s not worry about that for now.
In our example, the rollback is a call to the S.undo()
method. To simplify the example, let’s start with a rollback that calls a regular function, not a member function:
void undo(Storage& S) { S.undo(); }
Once...