General Utility Library for C++14  2.7
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 #include "gul14/internal.h"
29 
30 namespace gul14 {
31 
97 template <typename F>
99 {
100  F action_;
101  bool invoke_ {true};
102 
103 public:
116  explicit FinalAction(F f) noexcept
117  : action_(std::move(f))
118  {}
120  FinalAction(FinalAction&& other) noexcept
121  : action_{ std::move(other.action_) }
122  , invoke_{ other.invoke_ }
123  {
124  // don't call callback on moved from FinalAction
125  other.invoke_ = false;
126  }
128  FinalAction& operator=(FinalAction&& other) noexcept {
129  if (this != &other) {
130  this->action_ = std::move(other.action_);
131  this->invoke_ = std::move(other.invoke_);
132  // don't call callback on moved from FinalAction
133  other.invoke_ = false;
134  }
135  return *this;
136  }
137 
138  FinalAction() = delete;
139  FinalAction(const FinalAction&) = delete;
140  FinalAction& operator=(const FinalAction&) = delete;
141 
144  ~FinalAction() noexcept {
145  if (invoke_)
146  action_();
147  }
148 };
149 
161 template <typename F>
162 FinalAction<typename std::decay_t<F>> finally(F&& f) noexcept {
163  return FinalAction<typename std::decay_t<F>>(std::forward<typename std::decay_t<F>>(f));
164 }
165 
166 } // namespace gul14
167 
168 #endif
169 
170 // vi:et:sts=4:sw=4:ts=4
gul14::FinalAction::FinalAction
FinalAction()=delete
FinalAction is not is_default_constructible.
gul14::FinalAction::~FinalAction
~FinalAction() noexcept
Destructor Calls action except when in move contexts.
Definition: finalizer.h:144
gul14::FinalAction
FinalAction allows us to execute something if the FinalAction object leaves the scope.
Definition: finalizer.h:98
gul14::FinalAction::FinalAction
FinalAction(F f) noexcept
Creates a new FinalAction object.
Definition: finalizer.h:116
gul14::FinalAction::FinalAction
FinalAction(FinalAction &&other) noexcept
Move constructor.
Definition: finalizer.h:120
internal.h
Definition of macros used internally by GUL.
gul14
Namespace gul14 contains all functions and classes of the General Utility Library.
Definition: doxygen.h:26
gul14::FinalAction::operator=
FinalAction & operator=(FinalAction &&other) noexcept
Move assignment operator.
Definition: finalizer.h:128