An inheritance-based way to make singleton classes in C++
Before downloading or using this product, make sure you understand and accept the terms of the license.
After downloading, make sure to follow the how to use instructions below; they're worth reading.
The Singleton Template is a C++ template class that allows you to define your own singleton classes as inheriting from a single base class.
This provides a few benefits over other techniques:
::getInstance()
method)
The singleton creation method in ::getInstance()
is via the "Meyers Singleton" technique, described in the book Effective C++ by Scott Meyers. So essentially, this class is a "Meyers Singleton C++ template class."
#include "tSingleton.h"
tSingleton<MyClass>
, where MyClass
is the name of your classprotected
virtual
friend class
statement similar to the example belowclass MyClass : public tSingleton<MyClass> { protected: //Members go here protected: MyClass(); public: virtual ~MyClass(); public: //Methods go here friend class tSingleton<MyClass>; };
Your MyClass
class will now have a ::getInstance()
method, which you can use to construct the class or get it's instance at runtime.
MyClass::getInstance();
MyClass* c = MyClass::getInstance(); if (c) { c->doStuff(); // Assuming you have a method called ::doStuff, this is how you'd call it }
MyClass::getInstance()->doStuff();
That's it! You should be good to go.
If you have a question not answered here, please feel free to contact me and ask.
MyClass
originally inherited from MyBase
; you would still follow the example above in setup with just a minor change at the beginning:class MyClass : public MyBase, public tSingleton<MyClass>
::getInstance
, memory will be written; this is not thread-safe so your first call to ::getInstance
should be on the main thread::getInstance
only reads memory, so this should be safe on any thread::getInstance
on the main thread whenever possibleIf you've found this project useful, please donate today!
July 5, 2016
December 21, 2015
November 15, 2015