ActiveLib
Loading...
Searching...
No Matches
Public Types | Public Member Functions | List of all members
active::utility::Defer Class Reference

A class to hold an action to be deferred until its scope is exited. More...

#include <Defer.h>

Public Types

using Action = std::function<void()>
 Deferred action function.
 

Public Member Functions

 Defer (const Action &action)
 
 Defer (Action &&action)
 
 Defer (Defer &&source)
 
 Defer (const Defer &)=delete
 
Deferoperator= (const Defer &)=delete
 
 ~Defer ()
 

Detailed Description

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.

Constructor & Destructor Documentation

◆ Defer() [1/3]

active::utility::Defer::Defer ( const Action & action)
inline

Constructor

Parameters
actionThe action to defer

◆ Defer() [2/3]

active::utility::Defer::Defer ( Action && action)
inline

Constructor

Parameters
actionThe action to defer

◆ Defer() [3/3]

active::utility::Defer::Defer ( Defer && source)
inline

Move constructor

Parameters
sourceThe object to move

◆ ~Defer()

active::utility::Defer::~Defer ( )
inline

Destructor


The documentation for this class was generated from the following file: