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
67
69 ScopeGuard(const ScopeGuard& guard) = delete;
70
76 : m_func(std::move(guard.m_func)),
77 m_engaged(std::move(guard.m_engaged))
78 {
79 guard.release();
80 }
81
82
86 ~ScopeGuard() noexcept
87 {
88 if (!isReleased()) {
89 m_func();
90 }
91 }
92
94 ScopeGuard& operator=(const ScopeGuard& guard) = delete;
95
98 void release()
99 {
100 m_engaged = false;
101 }
102
105 bool isReleased() const
106 {
107 return !m_engaged;
108 }
109
110private:
111 typename std::remove_reference<TFunc>::type m_func;
112 bool m_engaged;
113};
114
130template <typename TFunctor>
132{
133 return ScopeGuard<TFunctor>(std::forward<TFunctor>(func));
134}
135
157template <typename TFunc,
158 typename... TParams>
159auto makeScopeGuard(TFunc&& func, TParams... args) ->
160ScopeGuard<decltype(std::bind(std::forward<TFunc>(func),
161 std::forward<TParams>(args)...))>
162{
163 auto bindObj = std::bind(std::forward<TFunc>(func), std::forward<TParams>(args)...);
164 return ScopeGuard<decltype(bindObj)>(std::move(bindObj));
165}
166
167} // namespace util
168
169} // 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:98
~ScopeGuard() noexcept
Destructor.
Definition ScopeGuard.h:86
bool isReleased() const
Check whether the functor is released.
Definition ScopeGuard.h:105
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:159
ScopeGuard< TFunctor > makeScopeGuard(TFunctor &&func)
Create scope guard with provided functor.
Definition ScopeGuard.h:131
ScopeGuard(ScopeGuard &&guard)
Move constructor.
Definition ScopeGuard.h:75
ScopeGuard & operator=(const ScopeGuard &guard)=delete
No copy is allowed.
Main namespace for all classes / functions of COMMS library.
STL namespace.