Advertisement
fimas

Singleton

Sep 14th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. // singletone.cpp : Defines the entry point for the console application.
  2. //
  3. // A singleton is a class which can only be instantiated once. This
  4. // can be useful when you want an object to have shared single state
  5. // across your application. One way of thinking of singletons is like
  6. // global variables.  
  7.  
  8. #include "stdafx.h"
  9. #include <iostream>
  10.  
  11. class Singleton {
  12. public:
  13.     static Singleton& getInstance() {
  14.         static Singleton instance; // Guaranteed to be destroyed
  15.                                    // Instantiated on first use
  16.         return instance;
  17.     }
  18.  
  19.     int getCounter() {
  20.         return counter;
  21.     }
  22. private:
  23.     Singleton() : counter(0) { counter++; } // Constructor? (the {} brackets) are needed here
  24.     int counter;
  25. public:
  26.     // C++ 11
  27.     // ========
  28.     // We can use a better technique for deleting methods
  29.     // we don't want
  30.     Singleton(Singleton const&) = delete;
  31.     void operator= (Singleton const&) = delete;
  32. };
  33.  
  34.  
  35. int main()
  36. {
  37.     // Should print
  38.     // 1
  39.     // 1
  40.     // 1
  41.     // 1
  42.     std::cout << Singleton::getInstance().getCounter() << std::endl;
  43.     std::cout << Singleton::getInstance().getCounter() << std::endl;
  44.     std::cout << Singleton::getInstance().getCounter() << std::endl;
  45.     std::cout << Singleton::getInstance().getCounter() << std::endl;
  46.  
  47.     system("PAUSE");
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement