COMMS
Template library intended to help with implementation of communication protocols.
ScopeGuard.h
Go to the documentation of this file.
1 //
2 // Copyright 2012 - 2024 (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 <memory>
14 #include <functional>
15 #include <type_traits>
16 
17 namespace comms
18 {
19 
20 namespace util
21 {
22 
52 template <typename TFunc>
54 {
55 public:
60  explicit ScopeGuard(TFunc&& func)
61  : func_(std::forward<TFunc>(func)),
62  engaged_(true)
63  {
64  }
65 
66 
68  ScopeGuard(const ScopeGuard& guard) = delete;
69 
75  : func_(std::move(guard.func_)),
76  engaged_(std::move(guard.engaged_))
77  {
78  guard.release();
79  }
80 
81 
85  ~ScopeGuard() noexcept
86  {
87  if (!isReleased()) {
88  func_();
89  }
90  }
91 
93  ScopeGuard& operator=(const ScopeGuard& guard) = delete;
94 
97  void release()
98  {
99  engaged_ = false;
100  }
101 
104  bool isReleased() const
105  {
106  return !engaged_;
107  }
108 
109 private:
110  typename std::remove_reference<TFunc>::type func_;
111  bool engaged_;
112 };
113 
129 template <typename TFunctor>
131 {
132  return ScopeGuard<TFunctor>(std::forward<TFunctor>(func));
133 }
134 
156 template <typename TFunc,
157  typename... TParams>
158 auto makeScopeGuard(TFunc&& func, TParams... args) ->
159 ScopeGuard<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:54
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
ScopeGuard & operator=(const ScopeGuard &guard)=delete
No copy is allowed.
bool isReleased() const
Check whether the functor is released.
Definition: ScopeGuard.h:104
ScopeGuard(TFunc &&func)
Constructor.
Definition: ScopeGuard.h:60
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:74
Main namespace for all classes / functions of COMMS library.