fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. ////////////////////////////////////////////////////////////////////////////////////////
  5.  
  6. template<typename T>
  7. struct Holder {
  8. Holder() {
  9. std::cout << "Holder()::Holder()" << std::endl;
  10. if (!Self) Self = new T();
  11. Self->Init();
  12. }
  13. ~Holder() {
  14. if (Self) {
  15. Self->Cleanup();
  16. delete Self;
  17. std::cout << "~Holder()::Holder()" << std::endl;
  18. }
  19. }
  20. T* Self = nullptr;
  21. };
  22.  
  23. ////////////////////////////////////////////////////////////////////////////////////////
  24.  
  25. template <typename T>
  26. class Singleton {
  27. public:
  28. static T* Instance() {
  29. std::cout << "Singlton::Instance()" << std::endl;
  30. static Holder<T> Dummy;
  31. return Dummy.Self;
  32. }
  33. private:
  34. Singleton() = delete;
  35. Singleton(Singleton const&) = delete;
  36. Singleton& operator= (Singleton const&) = delete;
  37. Singleton(Singleton const&&) = delete;
  38. Singleton& operator= (Singleton const&&) = delete;
  39. };
  40.  
  41. class Global {
  42. public:
  43. int GetA() {
  44. cout << "GetA" << endl;
  45. return x-1;
  46. }
  47. int GetB() {
  48. cout << "GetB" << endl;
  49. return x+1;
  50. }
  51. void Init() {};
  52. void Cleanup() {};
  53. private:
  54. int x = 1;
  55. };
  56.  
  57. struct Test1Class {
  58. void Print() {
  59. cout << Singleton<Global>::Instance()->GetA() << endl;
  60. }
  61. };
  62.  
  63. struct Test2Class {
  64. void Print() {
  65. cout << Singleton<Global>::Instance()->GetB() << endl;
  66. }
  67. };
  68.  
  69.  
  70. int main() {
  71. Test1Class T1;
  72. Test2Class T2;
  73. T1.Print();
  74. T2.Print();
  75. return 0;
  76. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Singlton::Instance()
Holder()::Holder()
GetA
0
Singlton::Instance()
GetB
2
~Holder()::Holder()