Created
December 27, 2016 02:33
-
-
Save bskim45/d477186405675f15d483b354e7be8e61 to your computer and use it in GitHub Desktop.
Simple C++ Singleton Example
This file contains 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
// 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; | |
} |
This file contains 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
// 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