Skip to content

Instantly share code, notes, and snippets.

@Elnee
Created June 22, 2019 06:16
Show Gist options
  • Save Elnee/b95855b6906cdd2167d0a40e3a4e32cd to your computer and use it in GitHub Desktop.
Save Elnee/b95855b6906cdd2167d0a40e3a4e32cd to your computer and use it in GitHub Desktop.
Simple C++ singleton
#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