Skip to content

Instantly share code, notes, and snippets.

@vpiotr
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpiotr/0f44ea1541a079521cf3 to your computer and use it in GitHub Desktop.
Save vpiotr/0f44ea1541a079521cf3 to your computer and use it in GitHub Desktop.
// 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