Created
June 22, 2019 06:16
-
-
Save Elnee/b95855b6906cdd2167d0a40e3a4e32cd to your computer and use it in GitHub Desktop.
Simple C++ singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Singleton { | |
public: | |
static Singleton& instance(); | |
int increment() { return ++x; } | |
private: | |
Singleton() = default; | |
Singleton(const Singleton&) = delete; | |
int x = 0; | |
}; | |
Singleton& Singleton::instance() | |
{ | |
static Singleton singleton; | |
return singleton; | |
} | |
int main() | |
{ | |
cout << Singleton::instance().increment() << endl; // 1 | |
cout << Singleton::instance().increment() << endl; // 2 | |
cout << Singleton::instance().increment() << endl; // 3 | |
cout << Singleton::instance().increment() << endl; // 4 | |
cout << Singleton::instance().increment() << endl; // 5 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment