C++ Singleton Implementation
#pragma once
////////////////////////////////////////////////////////////
#include <cassert>
#ifdef __APPLE__
#define nullptr NULL
#endif
////////////////////////////////////////////////////////////
template <typename S>
class Singleton
{
public:
Singleton()
{
assert(!s_instance);
s_instance = static_cast<S*>(this);
}
virtual ~Singleton()
{
assert(s_instance);
s_instance = 0;
}
static S* Instance()
{
return s_instance;
}
private:
static S* s_instance;
};
template <typename S>
S* Singleton<S>::s_instance = nullptr;
////////////////////////////////////////////////////////////
How to use
////////////////////////////////////////////////////////////
#include "Singleton.h"
////////////////////////////////////////////////////////////
class App : public Singleton<App>
{
...
}
////////////////////////////////////////////////////////////
inline App* GetApp()
{
return App::Instance();
}
////////////////////////////////////////////////////////////