C/C++ Arena

Step 8 of 8

Challenge: a scope guard

RAII isn't only for memory. Any "undo" action (close a file, unlock a mutex, roll back a transaction, restore a setting) can be tied to a destructor, so it runs however the scope is left: normal end, early return, or an exception.

A scope guard holds a function and calls it in its destructor, unless you dismiss() it first (for example, because the operation succeeded and there's nothing to undo). Many large codebases have one; C++ proposals call it scope_exit.

std::function<void()> can hold any callable that takes no arguments, including a lambda.

Your turn: write class ScopeGuard:

Previous: The rule of zero