MovableOnScopeExit.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__MOVEABLE_ON_SCOPE_EXIT
18 #define COM_BORA_SOFTWARE__BALAU_TYPE__MOVEABLE_ON_SCOPE_EXIT
19 
20 #include <functional>
21 #include <memory>
22 
23 namespace Balau {
24 
37 class MovableOnScopeExit final {
41  public: template <typename FunctionT> explicit MovableOnScopeExit(FunctionT function)
42  : exiter(new ContainerImpl<FunctionT>(function)) {}
43 
47  public: MovableOnScopeExit(MovableOnScopeExit && rhs) noexcept
48  : exiter(std::move(rhs.exiter)) {}
49 
53  public: void clear() {
54  exiter->clear();
55  }
56 
60  public: void executeNow() {
61  exiter->executeNow();
62  }
63 
65 
66  public: MovableOnScopeExit(const MovableOnScopeExit &) = delete;
67  public: MovableOnScopeExit & operator = (const MovableOnScopeExit &) = delete;
68 
69  private: struct ContainerBase {
70  virtual ~ContainerBase() = default;
71  public: virtual void clear() = 0;
72  public: virtual void reset(std::function<void ()> function_) = 0;
73  public: virtual void executeNow() = 0;
74  };
75 
76  private: template <typename FunctionT> struct ContainerImpl : public ContainerBase {
77  explicit ContainerImpl(FunctionT function_) : function(function_) {}
78 
79  ~ContainerImpl() override {
80  function();
81  }
82 
83  ContainerImpl(const ContainerImpl &) = delete;
84  ContainerImpl & operator =(const ContainerImpl &) = delete;
85 
86  public: void clear() override {
87  function = [] () {};
88  }
89 
90  public: void executeNow() override {
91  function();
92  clear();
93  }
94 
95  friend class MovableOnScopeExit;
96  private: FunctionT function;
97  };
98 
99  private: std::unique_ptr<ContainerBase> exiter;
100 };
101 
102 } // namespace Balau
103 
104 #endif // COM_BORA_SOFTWARE__BALAU_TYPE__MOVEABLE_ON_SCOPE_EXIT
Run a function on scope exit (movable version).
Definition: MovableOnScopeExit.hpp:37
void executeNow()
Execute the function now and then clear it.
Definition: MovableOnScopeExit.hpp:60
The root Balau namespace.
Definition: ApplicationConfiguration.hpp:23
MovableOnScopeExit(MovableOnScopeExit &&rhs) noexcept
Move the scope exit running to a different instance.
Definition: MovableOnScopeExit.hpp:47
void clear()
Set to the function to NOP (cancels scheduled execution).
Definition: MovableOnScopeExit.hpp:53
MovableOnScopeExit(FunctionT function)
Run the function on scope exit.
Definition: MovableOnScopeExit.hpp:41