Skip to content

Instantly share code, notes, and snippets.

@bskim45
Created December 27, 2016 02:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bskim45/d477186405675f15d483b354e7be8e61 to your computer and use it in GitHub Desktop.
Save bskim45/d477186405675f15d483b354e7be8e61 to your computer and use it in GitHub Desktop.
Simple C++ Singleton Example
// C++ 11 way, thread-safe version, guaranteed to be destroyed.
// For further details, see §6.7 [stmt.dcl] p4 of C++ 11 standard
class Singleton
{
public:
static Singleton& instance();
Singleton(Singleton const&) = delete; // Don't forget to disable copy
void operator=(Singleton const&) = delete; // Don't forget to disable copy
private:
Singleton(); // forbid create instance outside
~Singleton(); // forbid to delete instance outside
};
// Constructor & Dectructor
Singleton::Singleton() {
}
Singleton::~Singleton() {
}
// methods
Singleton& Singleton::instance() {
// create instance by lazy initialization
// guaranteed to be destroyed
static Singleton instance;
return instance;
}
// C++ 98, non thread-safe version
class Singleton
{
public:
static Singleton * instance();
private:
Singleton(); // forbid create instance outside
~Singleton(); // forbid to delete instance outside
Singleton(Singleton const&); // Don't forget to disable copy
void operator=(Singleton const&); // Don't forget to disable copy
};
// Constructor & Dectructor
Singleton::Singleton() {
}
Singleton::~Singleton() {
}
// methods
Singleton * Singleton::instance() {
// create new instance if null
if(m_inst == NULL) {
m_inst = new Singleton();
}
return m_inst;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment