Last active
December 11, 2015 21:49
-
-
Save mrcaron/4665334 to your computer and use it in GitHub Desktop.
Working on a singleton implementation
This file contains hidden or 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
namespace Utils | |
{ | |
template <class T> | |
class Singleton | |
{ | |
public: | |
static T& Instance() | |
{ | |
if (MInstance == 0) | |
MInstance = new T(); | |
return *MInstance; | |
} | |
private: | |
// Data | |
static T* MInstance; | |
//Unique, Not Copyable | |
Singleton<T>(const T&) {} | |
Singleton<T>& operator=(const Singleton<T>&) {} | |
~Singleton<T>() {} | |
Singleton<T>() { atexit(&Cleanup); } | |
// cleanup | |
static void CleanUp() { delete MInstance; MInstance = 0; } | |
}; | |
template< typename T > | |
T *Singleton<T>::MInstance = NULL; | |
} | |
namespace Usage | |
{ | |
class Demo | |
{ | |
public void SayHi() { cout << "Hi" << endl; } | |
} | |
typedef Utils::Singleton<Demo> DemoSingleton; | |
void UseSingleton() | |
{ | |
Demo& d = DemoSingleton::Instance(); | |
d.SayHi(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changed type of Demo, see http://stackoverflow.com/questions/14588143.