Skip to content

Instantly share code, notes, and snippets.

@BenEmdon
Created March 17, 2019 21:37
Show Gist options
  • Save BenEmdon/03ea764d5d115d628fe0094a293f48d7 to your computer and use it in GitHub Desktop.
Save BenEmdon/03ea764d5d115d628fe0094a293f48d7 to your computer and use it in GitHub Desktop.
C++ Singletons which don't leak
class Singleton {
public:
// Lazily get reference to a static instance of Singleton.
// The benifit of the following inplementation:
// * It lazily creates a Singleton.
// * It creates the Singleton on the global stack, so when the program ends
// the Singleton is automatically deallocated and it's deconstructor is invoked.
static Singleton& getInstance() {
// The following line (starting with `static`) only executes once,
// no matter how many times this function executes.
static Singleton singleton;
return shelter;
}
// The following line explicitly forbids the compiler from using a copy constructor. (C++11)
Singleton(const Singleton&) = delete;
~Singleton();
private:
// Keep the constructor private so that the only way to create the Singleton
// is through the `getInstance()` method.
Singleton();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment