scope_exit.h
Go to the documentation of this file.
1 #ifndef TTG_UTIL_SCOPE_EXIT_H
2 #define TTG_UTIL_SCOPE_EXIT_H
3 
4 //
5 // N4189: Scoped Resource - Generic RAII Wrapper for the Standard Library
6 // Peter Sommerlad and Andrew L. Sandoval
7 // Adopted from https://github.com/tandasat/ScopedResource/tree/master
8 //
9 
10 #include <type_traits>
11 
12 namespace ttg::detail {
13  template <typename EF>
14  struct scope_exit
15  {
16  // construction
17  explicit
18  scope_exit(EF &&f)
19  : exit_function(std::move(f))
20  , execute_on_destruction{ true }
21  { }
22 
23  // move
25  : exit_function(std::move(rhs.exit_function))
26  , execute_on_destruction{ rhs.execute_on_destruction }
27  {
28  rhs.release();
29  }
30 
31  // release
33  {
34  if (execute_on_destruction) this->exit_function();
35  }
36 
37  void release()
38  {
39  this->execute_on_destruction = false;
40  }
41 
42  private:
43  scope_exit(scope_exit const &) = delete;
44  void operator=(scope_exit const &) = delete;
45  scope_exit& operator=(scope_exit &&) = delete;
46  EF exit_function;
47  bool execute_on_destruction; // exposition only
48  };
49 
50  template <typename EF>
51  auto make_scope_exit(EF &&exit_function)
52  {
53  return scope_exit<std::remove_reference_t<EF>>(std::forward<EF>(exit_function));
54  }
55 
56 } // namespace ttg::detail
57 
58 #endif // TTG_UTIL_SCOPE_EXIT_H
auto make_scope_exit(EF &&exit_function)
Definition: scope_exit.h:51
scope_exit(scope_exit &&rhs)
Definition: scope_exit.h:24