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 - 2026 (C). Alex Robenko. All rights reserved.
3//
4// SPDX-License-Identifier: MPL-2.0
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
12
13#pragma once
14
15#include <functional>
16#include <type_traits>
17#include <utility>
18
19namespace comms
20{
21
22namespace util
23{
24
54template <typename TFunc>
56{
57public:
62 explicit ScopeGuard(TFunc&& func)
63 : m_func(std::forward<TFunc>(func)),
64 m_engaged(true)
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
85 ~ScopeGuard() noexcept
86 {
87 if (!isReleased()) {
88 m_func();
89 }
90 }
91
93 ScopeGuard& operator=(const ScopeGuard& guard) = delete;
94
97 void release()
98 {
99 m_engaged = false;
100 }
101
104 bool isReleased() const
105 {
106 return !m_engaged;
107 }
108
109private:
110 typename std::remove_reference<TFunc>::type m_func;
111 bool m_engaged;
112};
113
129template <typename TFunctor>
131{
132 return ScopeGuard<TFunctor>(std::forward<TFunctor>(func));
133}
134
156template <typename TFunc,
157 typename... TParams>
158auto makeScopeGuard(TFunc&& func, TParams... args) ->
159ScopeGuard<decltype(std::bind(std::forward<TFunc>(func),
160 std::forward<TParams>(args)...))>
161{
162 auto bindObj = std::bind(std::forward<TFunc>(func), std::forward<TParams>(args)...);
163 return ScopeGuard<decltype(bindObj)>(std::move(bindObj));
164}
165
166} // namespace util
167
168} // namespace comms
Implements Scope Guard Idiom.
Definition ScopeGuard.h:56
ScopeGuard(const ScopeGuard &guard)=delete
No copy is allowed.
void release()
Release the bound functor.
Definition ScopeGuard.h:97
~ScopeGuard() noexcept
Destructor.
Definition ScopeGuard.h:85
bool isReleased() const
Check whether the functor is released.
Definition ScopeGuard.h:104
ScopeGuard(TFunc &&func)
Constructor.
Definition ScopeGuard.h:62
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:158
ScopeGuard< TFunctor > makeScopeGuard(TFunctor &&func)
Create scope guard with provided functor.
Definition ScopeGuard.h:130
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.