Last active
August 29, 2015 14:13
-
-
Save vpiotr/0f44ea1541a079521cf3 to your computer and use it in GitHub Desktop.
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
// Basic singleton implementation | |
// Requires construction to be called before usage | |
// (so no lazy initialization) | |
// --- singleton.h | |
class Singleton { | |
public: | |
Singleton(); | |
virtual ~Singleton(); | |
static Singleton *getInstance() { | |
return m_activeSingleton; | |
} | |
//... | |
private: | |
static Singleton *m_activeSingleton; | |
}; | |
// --- singleton.cpp | |
Singleton* Singleton::m_activeSingleton = NULL; | |
Singleton::Singleton() | |
{ | |
if (m_activeSingleton == NULL) | |
m_activeSingleton = this; | |
} | |
Singleton::~Singleton() | |
{ | |
if (m_activeSingleton == this) | |
m_activeSingleton = NULL; | |
} | |
// --- derived class | |
class ConsoleLog: public Singleton { | |
public: | |
void addText(const std::string &a_text) { | |
cout << a_text; | |
} | |
static ConsoleLog *getInstance() { | |
return static_cast<ConsoleLog *>(Singleton::getInstance()); | |
} | |
}; | |
// --- main | |
void foo() { | |
ConsoleLog::getInstance()->addText("Test"); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
std::unique_ptr<ConsoleLog> consoleLog(new ConsoleLog); | |
foo(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment