template<typename TFunc>
class comms::util::ScopeGuard< TFunc >
Implements Scope Guard Idiom.
Scope guard idiom allows to call any function with any number of parameters when the guard is destructed, unless release() method is called prior to the destruction. The scope guard doesn't use any dynamic memory allocation and takes as much space on the stack as needed to bind the provided function with all its arguments. The template parameter must be type of the functor that doesn't receive any parameters and doesn't return any value. In order to properly create such guard use makeScopeGuard() function. For example:
auto guard = comms::util::makeScopeGuard(&func, std::ref(arg1), arg2);
auto guard =
comms::util::makeScopeGuard([&argByRef, argByValue]()
{
...
});
Note that all the bound parameters are passed by value, if there is any need to bind function with reference to some object, use "std::ref()" or "std::cref()" for const reference. Also note that the guard doesn't provide copy constructor and assignment operator, it supports only move semantics.
- Template Parameters
-
TFunc | Functor object type. |
template<typename TFunc , typename... TParams>
auto makeScopeGuard |
( |
TFunc && |
func, |
|
|
TParams... |
args |
|
) |
| -> ScopeGuard<decltype(std::bind(std::forward<TFunc>(func),
std::forward<TParams>(args)...))>
|
|
related |
Create scope guard by binding the provided function and all the arguments.
Use this function to create a scope guard when some function with one or more arguments needs to be called. For example:
auto guard = comms::util::makeScopeGuard(&func, std::ref(arg1), arg2);
Note that all the bound parameters are passed by value, if there is any need to bind function with reference to some object, use "std::ref()" or "std::cref()" for const reference. Also note that this function uses variadic template arguments which were introduced in C++11. Please make sure that you compiler supports it.
- Template Parameters
-
TFunc | Pointer to function type. |
TParams | Types of other arguments. |
- Parameters
-
[in] | func | Functor |
[in] | args | Function arguments |
- Returns
- Scope guard.