qxLib
destruction_callback.h
Go to the documentation of this file.
1 /**
2 
3  @file destruction_callback.h
4  @author Khrapov
5  @date 12.12.2021
6  @copyright (c) Nick Khrapov, 2021. All right reserved.
7 
8 **/
9 #pragma once
10 
12 
13 #include <functional>
14 #include <utility>
15 
16 namespace qx
17 {
18 
19 /**
20 
21  @class destruction_callback
22  @brief Class for RAII: functor passed in constructor will be called in destructor
23  @author Khrapov
24  @date 12.12.2021
25 
26 **/
27 class [[nodiscard]] destruction_callback
28 {
29 public:
30  using destroyer_type = std::function<void()>;
31 
32 public:
34 
35  destruction_callback() noexcept = default;
36 
37  /**
38  @brief destruction_callback object constructor
39  @tparam destroyer_t - callable type
40  @param destroyer - functor that will be called when object is destroyed
41  **/
42  template<class destroyer_t>
43  destruction_callback(destroyer_t destroyer);
44 
46 
47  destruction_callback& operator=(destruction_callback&& other) noexcept;
48 
50 
51 private:
52  destroyer_type m_Destroyer;
53 };
54 
55 inline destruction_callback::destruction_callback(destruction_callback&& other) noexcept
56 {
57  std::swap(m_Destroyer, other.m_Destroyer);
58 }
59 
60 inline destruction_callback& destruction_callback::operator=(destruction_callback&& other) noexcept
61 {
62  std::swap(m_Destroyer, other.m_Destroyer);
63  return *this;
64 }
65 
66 inline destruction_callback::~destruction_callback()
67 {
68  if (m_Destroyer)
69  m_Destroyer();
70 }
71 
72 template<class destroyer_t>
73 destruction_callback::destruction_callback(destroyer_t destroyer) : m_Destroyer(std::move(destroyer))
74 {
75 }
76 
77 } // namespace qx
Class for RAII: functor passed in constructor will be called in destructor.
#define QX_NONCOPYABLE(className)
Define class as non copyable.