openMSX
scope_exit.hh
Go to the documentation of this file.
1 #ifndef SCOPE_EXIT_HH
2 #define SCOPE_EXIT_HH
3 
4 // Simplified version of
5 // https://en.cppreference.com/w/cpp/experimental/scope_exit
6 //
7 // Typically used to execute some cleanup action whenever a certain scope is
8 // left. Either via the fall-through code path, a return/break/continue or via
9 // an exception.
10 //
11 // Example usage:
12 // bool f() {
13 // char* ptr = some_c_style_function_that_returns_an_owning_pointer()
14 // scope_exit e([&]{ free(ptr); });
15 // if (some_check(ptr)) return false; // 1
16 // stuff_which_might_throw(); // 2
17 // return true; // 3
18 // }
19 //
20 // Note: 'free(ptr)' is called when we exit the function via 1) 2) or 3)
21 
22 #include <utility>
23 
24 template<typename FUNC>
26 {
27 public:
28  explicit scope_exit(FUNC&& action_)
29  : action(std::forward<FUNC>(action_))
30  {
31  }
32 
34  {
35  action();
36  }
37 
38 private:
39  FUNC action;
40 };
41 
42 #endif
scope_exit::scope_exit
scope_exit(FUNC &&action_)
Definition: scope_exit.hh:28
scope_exit
Definition: scope_exit.hh:26
scope_exit::~scope_exit
~scope_exit()
Definition: scope_exit.hh:33