hmbdc
simplify-high-performance-messaging-programming
GuardedSingleton.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 
4 #include "hmbdc/Exception.hpp"
5 #include <stdexcept>
6 #include <type_traits>
7 #include <typeinfo>
8 
9 namespace hmbdc { namespace pattern {
10 /**
11  * @class SingletonGuardian<>
12  * @brief RAII representing the lifespan of the underlying Singleton
13  * which also ganrantees the singularity of underlying Singleton
14  * @details when the SingletonGuardian is constructored, the underlying Singleton is created;
15  * when the SingletonGuardian goes out of scope the dtor of the Singleton is called.
16  *
17  * @tparam Singleton the underlying type, which needs to be derived from GuardedSingleton
18  */
19 template <typename Singleton>
21  template <typename...Args>
22  SingletonGuardian(Args&&...);
23  virtual ~SingletonGuardian();
24 };
25 
26 /**
27  * @class GuardedSingleton<>
28  * @brief base for the Singleton that works with SingletonGuardian
29  * @details a good practice is to declare the ctor of the derived class private
30  * and friend the derived with the SingletonGuardian<derived>
31  *
32  * @tparam Singleton the derived type
33  */
34 template<typename Singleton>
36  friend struct SingletonGuardian<Singleton>;
37  static Singleton& instance() {return *pInstance_s;}
38  static bool initialized() {return pInstance_s;}
39  using element_type = Singleton;
40 
41 protected:
42  GuardedSingleton() = default;
43 
44 private:
45  static Singleton* pInstance_s;
46 };
47 
48 template <typename Singleton> Singleton*
50 
51 template <typename Singleton>
52 template <typename...Args>
54 SingletonGuardian(Args&&...args) {
55  if (GuardedSingleton<Singleton>::pInstance_s) {
56  HMBDC_THROW(std::runtime_error
57  , "Cannot reinitialize typeid=" << typeid(Singleton).name());
58  }
59  GuardedSingleton<Singleton>::pInstance_s
60  = new Singleton(std::forward<Args>(args)...);
61 }
62 
63 template <typename Singleton>
66  delete GuardedSingleton<Singleton>::pInstance_s;
67  GuardedSingleton<Singleton>::pInstance_s = 0;
68 }
69 
70 }}
71 
72 
base for the Singleton that works with SingletonGuardian
Definition: GuardedSingleton.hpp:35
RAII representing the lifespan of the underlying Singleton which also ganrantees the singularity of u...
Definition: GuardedSingleton.hpp:20
Definition: Base.hpp:12