fork download
  1. #include <bits/stdc++.h>
  2. #include <memory>
  3. #include <iostream>
  4.  
  5. template <typename T>
  6. class SingletonBase {
  7. public:
  8. static std::shared_ptr<T> m_Instance;
  9.  
  10. SingletonBase() {
  11. std::cout << "Calling base constructor" << std::endl;
  12. }
  13.  
  14. static std::shared_ptr<T> GetInstance() {
  15. std::cout << "Calling GetInstance" << std::endl;
  16.  
  17. if (m_Instance == nullptr) {
  18. m_Instance = std::shared_ptr<T>(new T);
  19. }
  20.  
  21. return m_Instance;
  22. }
  23.  
  24. void Init() {
  25. if (m_Instance) {
  26. std::cout << "Init called" << std::endl;
  27. } else {
  28. std::cout << "Init not called" << std::endl;
  29. }
  30. }
  31. };
  32.  
  33. template <typename T>
  34. std::shared_ptr<T> SingletonBase<T>::m_Instance = nullptr;
  35.  
  36. class Derived : public SingletonBase<Derived> {
  37. public:
  38. Derived() {
  39. std::cout << "Calling Derived constructor" << std::endl;
  40. }
  41. };
  42.  
  43. class Derived2 : public SingletonBase<Derived2> {
  44. public:
  45. Derived2() {
  46. std::cout << "Calling Derived2 constructor" << std::endl;
  47. }
  48. };
  49.  
  50. using namespace std;
  51.  
  52. int main() {
  53. std::shared_ptr<Derived> d1;
  54. d1 = Derived::GetInstance();
  55. d1->Init();
  56.  
  57. std::shared_ptr<Derived2> d2;
  58. d2 = Derived2::GetInstance();
  59. d2->Init();
  60. std::cout << " - ------";
  61. std::shared_ptr<Derived2> d3;
  62. d3 = Derived2::GetInstance();
  63. d3->Init();
  64. return 0;
  65. }
Success #stdin #stdout 0.01s 5284KB
stdin
45
stdout
Calling GetInstance
Calling base constructor
Calling Derived constructor
Init called
Calling GetInstance
Calling base constructor
Calling Derived2 constructor
Init called
 -         ------Calling GetInstance
Init called