rs-core

Core utilities


Project maintained by CaptainCrowbar Hosted on GitHub Pages — Theme by mattgraham

Scope Guards

Core utility library by Ross Smith

#include "rs-core/scope.hpp"
namespace RS;

Contents

Scope guards

enum class ScopeMode: unsigned char {
    success  = 1,
    failure  = 2,
    exit     = success | failure,
};

This is used to control the behaviour of a scope guard:

template <std::invocable F, ScopeMode M> class BasicScopeGuard {
    explicit BasicScopeGuard(F&& f);
    ~BasicScopeGuard() noexcept;
    void release() noexcept;
};

The basic scope guard object. This is normally created using one of the functions below rather than being explicitly constructed. The callback type F must be a function object that can be called with no arguments.

Calling release() cancels all destructor behaviour; the callback will never be invoked after release.

Behaviour is undefined if the callback is a null function pointer or std::function, or if the callback’s function call operator, or its copy or move constructor, throws an exception.

template <std::invocable F> [scope guard] on_success(F&& f);
template <std::invocable F> [scope guard] on_failure(F&& f);
template <std::invocable F> [scope guard] on_exit(F&& f);

These construct scope guards that will invoke their callbacks under the appropriate conditions.

Scope guard utilities

template <[resizeable container] T> [scope guard] guard_size(T& t);

Creates a scope guard that will restore the previous size of a container on failure. This does not attempt to preserve element values, only the number of elements.

template <std::copyable T> [scope guard] guard_value(T& t);

Creates a scope guard that will restore the previous value of a variable on failure.