1 #ifndef OT_UTILITY_SCOPE_GUARD_HPP_ 2 #define OT_UTILITY_SCOPE_GUARD_HPP_ 3 4 namespace ot { 5 6 template <typename F> 7 class ScopeGuard { 8 9 private: 10 11 F _f; 12 bool _active; 13 14 public: 15 ScopeGuard(F && f)16 ScopeGuard(F&& f) : _f {std::forward<F>(f)}, _active {true} { 17 } 18 ~ScopeGuard()19 ~ScopeGuard() { 20 if(_active) _f(); 21 } 22 dismiss()23 void dismiss() noexcept { 24 _active = false; 25 } 26 27 ScopeGuard() = delete; 28 ScopeGuard(const ScopeGuard&) = delete; 29 ScopeGuard& operator = (const ScopeGuard&) = delete; 30 ScopeGuard& operator = (ScopeGuard&&) = delete; 31 ScopeGuard(ScopeGuard && rhs)32 ScopeGuard(ScopeGuard&& rhs) : _f{std::move(rhs._f)}, _active {rhs._active} { 33 rhs.dismiss(); 34 } 35 }; 36 37 template <typename F> ScopeGuard(F&&) -> ScopeGuard<F>; 38 39 template <typename F> make_scope_guard(F && f)40auto make_scope_guard(F&& f) { 41 return ScopeGuard<F>(std::forward<F>(f)); 42 } 43 44 45 }; // end of namespace dtc. ---------------------------------------------------------------------- 46 47 48 49 #endif 50