stlab 2.3.0
Modern, modular C++ algorithms, data structures, and concurrency primitives
Loading...
Searching...
No Matches
scope.hpp File Reference

Bind an object’s lifetime to a callable’s execution (scope). More...

#include <stlab/config.hpp>
#include <mutex>
#include <tuple>
#include <utility>

Go to the source code of this file.

Functions

template<typename T, typename... Args>
auto stlab::scope (Args &&... args)
 Scopes the lifetime of an instance of T. All but the last arguments construct T; the last argument is a nullary function invoked while T is alive. T is destroyed after that function returns.
template<typename T, typename F>
auto stlab::scope (std::mutex &m, F &&f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Detailed Description

Bind an object’s lifetime to a callable’s execution (scope).

Motivation
A plain extra { } block does not document intent. scope constructs T from the leading arguments, runs the last argument as a nullary function while T is alive, then destroys T.
Example
void pop_and_run_task() {
std::function<void()> task = scope<std::lock_guard<std::mutex>>(m, [&]() {
return pop_front_unsafe(task_queue);
});
task();
}
The lock’s lifetime is bound to the lambda that pops the queue—clearer than an anonymous scope.