Advertisement
llsumitll

SingletonClass.cpp

Jul 10th, 2023
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | Source Code | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. class Singleton
  4. {
  5.     private:
  6.         Singleton() {};
  7.         Singleton(Singleton& ) = delete;
  8.         Singleton operator=(Singleton&) = delete;
  9.        
  10.     public:
  11.         static Singleton * instance;
  12.         static Singleton * getInstance();
  13.  
  14.         void foo() { cout << "test object" << endl;}
  15. };
  16.  
  17. Singleton * Singleton::instance = nullptr;
  18. //Singleton * getInstance()
  19. Singleton * Singleton::getInstance()
  20.         {
  21.             if (Singleton::instance ==  nullptr)
  22.             {
  23.                 Singleton::instance = new Singleton();
  24.             }
  25.             return Singleton::instance;
  26.         }
  27. int main()
  28. {
  29.   // Singleton * s = new Singleton(); // error  
  30.   Singleton* ss = Singleton::getInstance();
  31.   Singleton* aa = Singleton::getInstance();
  32.   cout << ss << endl;
  33.   cout << aa << endl;
  34.  
  35.   return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement