OnScopeExit.hpp
Go to the documentation of this file.
1 // @formatter:off
2 //
3 // Balau core C++ library
4 //
5 // Copyright (C) 2008 Bora Software (contact@borasoftware.com)
6 //
7 // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003.
8 // See the LICENSE file for the full license text.
9 //
10 
16 
17 #ifndef COM_BORA_SOFTWARE__BALAU_TYPE__ON_SCOPE_EXIT
18 #define COM_BORA_SOFTWARE__BALAU_TYPE__ON_SCOPE_EXIT
19 
20 #include <functional>
21 
22 namespace Balau {
23 
34 class OnScopeExit final {
38  public: explicit OnScopeExit(std::function<void ()> function_)
39  : function(std::move(function_)) {}
40 
44  public: ~OnScopeExit() {
45  function();
46  }
47 
51  public: void clear() {
52  function = [] () {};
53  }
54 
58  public: void rest(std::function<void ()> function_) {
59  function = function_;
60  }
61 
65  public: void executeNow() {
66  function();
67  clear();
68  }
69 
71 
72  public: OnScopeExit() = delete;
73  public: OnScopeExit(const OnScopeExit &) = delete;
74  public: OnScopeExit & operator = (const OnScopeExit &) = delete;
75 
76  private: std::function<void ()> function;
77 };
78 
79 } // namespace Balau
80 
81 #endif // COM_BORA_SOFTWARE__BALAU_TYPE__ON_SCOPE_EXIT
STL namespace.
The root Balau namespace.
Definition: ApplicationConfiguration.hpp:23
Run a function on scope exit.
Definition: OnScopeExit.hpp:34
void clear()
Set to the function to NOP (cancels scheduled execution).
Definition: OnScopeExit.hpp:51
void executeNow()
Execute the function now and then clear it.
Definition: OnScopeExit.hpp:65
OnScopeExit(std::function< void()> function_)
Run the function on scope exit.
Definition: OnScopeExit.hpp:38
~OnScopeExit()
Run the scope exit function and destroy the OnScopeExit instance.
Definition: OnScopeExit.hpp:44
void rest(std::function< void()> function_)
Set to the function to a different function (cancels previously scheduled execution).
Definition: OnScopeExit.hpp:58