Last active
January 5, 2022 03:53
-
-
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
This file contains hidden or 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
// 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; |
This file contains hidden or 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
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