Skip to content

Instantly share code, notes, and snippets.

@mrcaron
Last active December 11, 2015 21:49
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 mrcaron/4665334 to your computer and use it in GitHub Desktop.
Save mrcaron/4665334 to your computer and use it in GitHub Desktop.
Working on a singleton implementation
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();
}
}
@mrcaron
Copy link
Author

mrcaron commented Jan 29, 2013

Changed type of Demo, see http://stackoverflow.com/questions/14588143.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment