COMMS
Template library intended to help with implementation of communication protocols.
Loading...
Searching...
No Matches
ScopeGuard.h
Go to the documentation of this file.
1//
2// Copyright 2012 - 2025 (C). Alex Robenko. All rights reserved.
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
10
11#pragma once
12
13#include <functional>
14#include <memory>
15#include <type_traits>
16#include <utility>
17
18namespace comms
19{
20
21namespace util
22{
23
53template <typename TFunc>
55{
56public:
61 explicit ScopeGuard(TFunc&& func)
62 : m_func(std::forward<TFunc>(func)),
63 m_engaged(true)
64 {
65 }
66
68 ScopeGuard(const ScopeGuard& guard) = delete;
69
75 : m_func(std::move(guard.m_func)),
76 m_engaged(std::move(guard.m_engaged))
77 {
78 guard.release();
79 }
80
84 ~ScopeGuard() noexcept
85 {
86 if (!isReleased()) {
87 m_func();
88 }
89 }
90
92 ScopeGuard& operator=(const ScopeGuard& guard) = delete;
93
96 void release()
97 {
98 m_engaged = false;
99 }
100
103 bool isReleased() const
104 {
105 return !m_engaged;
106 }
107
108private:
109 typename std::remove_reference<TFunc>::type m_func;
110 bool m_engaged;
111};
112
128template <typename TFunctor>
130{
131 return ScopeGuard<TFunctor>(std::forward<TFunctor>(func));
132}
133
155template <typename TFunc,
156 typename... TParams>
157auto makeScopeGuard(TFunc&& func, TParams... args) ->
158ScopeGuard<decltype(std::bind(std::forward<TFunc>(func),
159 std::forward<TParams>(args)...))>
160{
161 auto bindObj = std::bind(std::forward<TFunc>(func), std::forward<TParams>(args)...);
162 return ScopeGuard<decltype(bindObj)>(std::move(bindObj));
163}
164
165} // namespace util
166
167} // namespace comms
Implements Scope Guard Idiom.
Definition ScopeGuard.h:55
ScopeGuard(const ScopeGuard &guard)=delete
No copy is allowed.
void release()
Release the bound functor.
Definition ScopeGuard.h:96
~ScopeGuard() noexcept
Destructor.
Definition ScopeGuard.h:84
bool isReleased() const
Check whether the functor is released.
Definition ScopeGuard.h:103
ScopeGuard(TFunc &&func)
Constructor.
Definition ScopeGuard.h:61
auto makeScopeGuard(TFunc &&func, TParams... args) -> ScopeGuard< decltype(std::bind(std::forward< TFunc >(func), std::forward< TParams >(args)...))>
Create scope guard by binding the provided function and all the arguments.
Definition ScopeGuard.h:157
ScopeGuard< TFunctor > makeScopeGuard(TFunctor &&func)
Create scope guard with provided functor.
Definition ScopeGuard.h:129
ScopeGuard(ScopeGuard &&guard)
Move constructor.
Definition ScopeGuard.h:74
ScopeGuard & operator=(const ScopeGuard &guard)=delete
No copy is allowed.
Main namespace for all classes / functions of COMMS library.
STL namespace.