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 
40 protected:
41  GuardedSingleton() = default;
42 
43 private:
44  static Singleton* pInstance_s;
45 };
46 
47 template <typename Singleton> Singleton*
49 
50 template <typename Singleton>
51 template <typename...Args>
53 SingletonGuardian(Args&&...args) {
54  if (GuardedSingleton<Singleton>::pInstance_s) {
55  HMBDC_THROW(std::runtime_error
56  , "Cannot reinitialize typeid=" << typeid(Singleton).name());
57  }
58  GuardedSingleton<Singleton>::pInstance_s
59  = new Singleton(std::forward<Args>(args)...);
60 }
61 
62 template <typename Singleton>
65  delete GuardedSingleton<Singleton>::pInstance_s;
66  GuardedSingleton<Singleton>::pInstance_s = 0;
67 }
68 
69 }}
70 
71 
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