Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Last active January 5, 2022 03:53
Show Gist options
  • Save jniemann66/79f9c3eafb7920c1d969d57d68cd4e94 to your computer and use it in GitHub Desktop.
Save jniemann66/79f9c3eafb7920c1d969d57d68cd4e94 to your computer and use it in GitHub Desktop.
Singletons: (1) canonical GoF Singleton Pattern for C++ (2) Scott Meyer's (C++11) singleton
// http://www.gofpatterns.com/design-patterns/module3/cplus-plus-singleton.php
class Singleton {
private:
static Singleton* theInstance;
protected:
Singleton();
public:
static Singleton* getInstance(){
if (theInstance == 0 ) {
theInstance = new Singleton();
}
return theInstance;
};
};
Singleton* Singleton::theInstance = 0;
class Singleton
{
public:
static Singleton& instance()
{
static Singleton s; // initialized the first time control passes to this declaration. Ignored on subsequent calls.
// Since C++11, If multiple threads attempt to initialize the same static local variable concurrently,
// the initialization is still guaranteed to occur exactly once.
// see https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables
return s;
}
private:
Singleton() {}
Singleton(const Singleton &) = delete;
Singleton& operator= (const Singleton &) = delete;
~Singleton() {}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment