distortos  v0.7.0
object-oriented C++ RTOS for microcontrollers
ScopeGuard.hpp
Go to the documentation of this file.
1 
12 #ifndef ESTD_SCOPEGUARD_HPP_
13 #define ESTD_SCOPEGUARD_HPP_
14 
15 #include <utility>
16 
17 namespace estd
18 {
19 
29 template<typename Function>
31 {
32 public:
33 
40  constexpr explicit ScopeGuard(Function&& function) noexcept :
41  function_{std::move(function)},
42  released_{}
43  {
44 
45  }
46 
53  ScopeGuard(ScopeGuard&& other) noexcept :
54  function_(std::move(other.function_)),
55  released_{other.released_}
56  {
57  other.release();
58  }
59 
66  ~ScopeGuard() noexcept
67  {
68  if (released_ == false)
69  function_();
70  }
71 
78  void release() noexcept
79  {
80  released_ = true;
81  }
82 
83  ScopeGuard(const ScopeGuard&) = delete;
84  ScopeGuard& operator=(const ScopeGuard&) = delete;
85  ScopeGuard& operator=(ScopeGuard&&) = delete;
86 
87 private:
88 
90  Function function_;
91 
93  bool released_;
94 };
95 
106 template <typename Function>
107 ScopeGuard<Function> makeScopeGuard(Function&& function) noexcept
108 {
109  return ScopeGuard<Function>{std::move(function)};
110 }
111 
112 } // namespace estd
113 
114 #endif // ESTD_SCOPEGUARD_HPP_
Collection of useful templates.
Definition: DmaChannel.hpp:121
Function function_
function executed on scope exit
Definition: ScopeGuard.hpp:90
ScopeGuard< Function > makeScopeGuard(Function &&function) noexcept
Helper factory function to make ScopeGuard object with deduced template arguments.
Definition: ScopeGuard.hpp:107
void release() noexcept
Releases ScopeGuard.
Definition: ScopeGuard.hpp:78
~ScopeGuard() noexcept
ScopeGuard's destructor.
Definition: ScopeGuard.hpp:66
ScopeGuard template class is a idiom introduced by Andrei Alexandrescu and proposed for C++14 in N394...
Definition: ScopeGuard.hpp:30
ScopeGuard(ScopeGuard &&other) noexcept
ScopeGuard's move constructor.
Definition: ScopeGuard.hpp:53
bool released_
true if object is released (bound function will not be executed), false otherwise
Definition: ScopeGuard.hpp:93
constexpr ScopeGuard(Function &&function) noexcept
ScopeGuard's constructor.
Definition: ScopeGuard.hpp:40