The use is to provide .instance access, also to prevent duplicate objects of those classes.
Is this a good code implementation of a singleton?
template <typename T> class singleton
{
public:
static T *ms_singleton;
singleton()
{
assert(!ms_singleton);
long offset = (long)(T *) 1 - (long)(singleton <T> *)(T *) 1;
ms_singleton = (T *)((long) this + offset);
}
virtual ~singleton()
{
assert(ms_singleton);
ms_singleton = 0;
}
static T &instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
static T &Instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
static T *instance_ptr()
{
return (ms_singleton);
}
};
template <typename T> T *singleton <T>::ms_singleton = NULL;
How I use it:
class test1: public singleton<test2>
{
// Something
};
If not, what is wrong here? What should i rewrite here?