A class to hold an action to be deferred until its scope is exited.
Used in cases where some action must be taken before a specific scope exits, often a 'closing' action counterbalancing some corresponding
'opening' action, e.g. balancing unlocking a mutex with locking it, and particulary where there may be multiple paths or exit points within
the context. This is sometimes handled by writing a block of exit code and jumping to it from every exit point with 'goto'. But this can be
hard to read and it's far too easy to either omit a necessary action or fail to jump to the correct exit point.
Some languages incorporate an explicit 'defer' statement for this purpose, e.g.:
opening statement
defer {
closing statement
}
This pattern ensures the closing statement is executed no matter how the scope is exited. The `Defer` class provides the same pattern
in C++, e.g.:
auto fooResource = aquireFooResource();
auto scope = defer([&]{
releaseFooResource(fooResource);
});
...more code in this scope with multiple exit points
NB: The variable name in this example (`scope`) has no significance. When the variable goes out of scope (including a thrown exception)
the lambda will be executed. There can be any number of these in any given scope, so immediately follow any opening statement with a the
corresponding `defer`. This will guarantee the required code is executed.