Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // singletone.cpp : Defines the entry point for the console application.
- //
- // A singleton is a class which can only be instantiated once. This
- // can be useful when you want an object to have shared single state
- // across your application. One way of thinking of singletons is like
- // global variables.
- #include "stdafx.h"
- #include <iostream>
- class Singleton {
- public:
- static Singleton& getInstance() {
- static Singleton instance; // Guaranteed to be destroyed
- // Instantiated on first use
- return instance;
- }
- int getCounter() {
- return counter;
- }
- private:
- Singleton() : counter(0) { counter++; } // Constructor? (the {} brackets) are needed here
- int counter;
- public:
- // C++ 11
- // ========
- // We can use a better technique for deleting methods
- // we don't want
- Singleton(Singleton const&) = delete;
- void operator= (Singleton const&) = delete;
- };
- int main()
- {
- // Should print
- // 1
- // 1
- // 1
- // 1
- std::cout << Singleton::getInstance().getCounter() << std::endl;
- std::cout << Singleton::getInstance().getCounter() << std::endl;
- std::cout << Singleton::getInstance().getCounter() << std::endl;
- std::cout << Singleton::getInstance().getCounter() << std::endl;
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement