qxLib
singleton.h
Go to the documentation of this file.
1 /**
2 
3  @file singleton.h
4  @author Khrapov
5  @date 17.06.2019
6  @copyright © Nick Khrapov, 2021. All right reserved.
7 
8 **/
9 #pragma once
10 
11 #include <qx/macros/common.h>
12 
13 namespace qx
14 {
15 
16 /**
17  @struct singleton_traits
18  @tparam T - singleton class
19 **/
20 template<class T>
22 {
23  /**
24  @brief Called when singleton constructed
25  @param instance - singleton instance
26  **/
27  static void on_constructed(T& instance)
28  {
29  }
30 
31  /**
32  @brief Called when singleton proceeds getter
33  @param instance - singleton instance
34  **/
35  static void on_getter(T& instance)
36  {
37  }
38 
39  /**
40  @brief Called before singleton destructed
41  @param instance - singleton instance
42  **/
43  static void on_destructed(T& instance)
44  {
45  }
46 };
47 
48 } // namespace qx
49 
50 /**
51  @def QX_SINGLETON_S
52  @brief Simple Meyer's singleton
53  @details Implement singleton_traits for your type to change creation,
54  getting and destruction behaviour
55  @param T - your class type
56  @param specifiers - type specifiers, such as "static" or "thread_safe"
57 **/
58 #define QX_SINGLETON_S(T, specifiers) \
59 private: \
60  friend struct qx::singleton_traits<T>; \
61  \
62  T() \
63  { \
64  qx::singleton_traits<T>::on_constructed(*this); \
65  } \
66  ~T() \
67  { \
68  qx::singleton_traits<T>::on_destructed(*this); \
69  } \
70  T(const T&) = delete; \
71  T(T&&) = delete; \
72  const T& operator=(const T&) = delete; \
73  const T& operator=(T&&) = delete; \
74  \
75 public: \
76  static T& get_instance() \
77  { \
78  specifiers T instance; \
79  qx::singleton_traits<T>::on_getter(instance); \
80  return instance; \
81  } \
82  \
83 private: \
84  QX_EMPTY_MACRO
85 
86 /**
87  @def QX_SINGLETON
88  @details Implement singleton_traits for your type to change creation,
89  getting and destruction behaviour
90  @brief Simple Meyer's singleton
91  @param T - your class type
92 **/
93 #define QX_SINGLETON(T) QX_SINGLETON_S(T, static)
static void on_getter(T &instance)
Called when singleton proceeds getter.
Definition: singleton.h:35
static void on_destructed(T &instance)
Called before singleton destructed.
Definition: singleton.h:43
static void on_constructed(T &instance)
Called when singleton constructed.
Definition: singleton.h:27