General Utility Library for C++14  2.12
finalizer.h
Go to the documentation of this file.
1 
23 #ifndef GUL14_FINALIZER_H_
24 #define GUL14_FINALIZER_H_
25 
26 #include <type_traits>
27 #include <utility>
28 
29 #include "gul14/internal.h"
30 
31 namespace gul14 {
32 
104 template <typename F>
106 {
107  F action_;
108  bool invoke_ {true};
109 
110 public:
123  explicit FinalAction(F f) noexcept
124  : action_(std::move(f))
125  {}
127  FinalAction(FinalAction&& other) noexcept
128  : action_{ std::move(other.action_) }
129  , invoke_{ other.invoke_ }
130  {
131  // don't call callback on moved from FinalAction
132  other.invoke_ = false;
133  }
135  FinalAction& operator=(FinalAction&& other) noexcept {
136  if (this != &other) {
137  this->action_ = std::move(other.action_);
138  this->invoke_ = std::move(other.invoke_);
139  // don't call callback on moved from FinalAction
140  other.invoke_ = false;
141  }
142  return *this;
143  }
144 
145  FinalAction() = delete;
146  FinalAction(const FinalAction&) = delete;
147  FinalAction& operator=(const FinalAction&) = delete;
148 
151  ~FinalAction() noexcept {
152  if (invoke_)
153  action_();
154  }
155 };
156 
168 template <typename F>
169 FinalAction<typename std::decay_t<F>> finally(F&& f) noexcept {
170  return FinalAction<typename std::decay_t<F>>(std::forward<typename std::decay_t<F>>(f));
171 }
172 
174 
175 } // namespace gul14
176 
177 #endif
178 
179 // vi:et:sts=4:sw=4:ts=4
FinalAction allows us to execute something if the FinalAction object leaves the scope.
Definition: finalizer.h:106
FinalAction & operator=(const FinalAction &)=delete
FinalAction is not copyable.
FinalAction & operator=(FinalAction &&other) noexcept
Move assignment operator.
Definition: finalizer.h:135
~FinalAction() noexcept
Destructor Calls action except when in move contexts.
Definition: finalizer.h:151
FinalAction(const FinalAction &)=delete
FinalAction is not copyable.
FinalAction(FinalAction &&other) noexcept
Move constructor.
Definition: finalizer.h:127
FinalAction()=delete
FinalAction is not is_default_constructible.
FinalAction(F f) noexcept
Creates a new FinalAction object.
Definition: finalizer.h:123
Definition of macros used internally by GUL.
Namespace gul14 contains all functions and classes of the General Utility Library.
Definition: doxygen.h:26