I inhereted an implementation of a singleton template. Althoug I read that singletons are bad, my program uses singletons throughout and I can not get rid of them at the moment.
This is the implementation I started with:
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;
And the new implementation.
#pragma once
template<typename T>
class Singleton
{
public:
static T &Instance()
{
static T* myInstance;
return (*myInstance);
}
Singleton(Singleton const &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(Singleton const &) = delete;
Singleton &operator=(Singleton &&) = delete;
protected:
Singleton() = default;
virtual ~Singleton() = default;
};
The first code doesn't create the class and only sets a pointer to an existing instance; the new implementation does the same.
Do you think the second implementation is correct? Is there something that should be optimized or changed? There may be problems if I use it like that? Should I also handle the creation of classes?
This new implementation should behave the same as first, because I have a big project and I just can't get rid of this singleton.
How good is the new singleton?