Need "simple" singleton class example

Started by
32 comments, last by johnnyBravo 20 years, 5 months ago
Here''s a very simple templated singleton. The only drawback is that unless you create templated derivatives you won''t be able to derive more than once.

template<typename T>class Singleton{public:		static T& GetInstance(){static T s; return s;}protected:	Singleton(){}	Singleton(const Singleton&){}	Singleton& operator=(const Singleton&){}	~Singleton(){}};class Derived : public Singleton<Derived>{public:        void Blah(){}};


Here''s how you use it:

Derived &d = Derived::GetInstance();d.Blah();orDerived::GetInstance().Blah();


Ok, here is the creation of a chain of what I had in mind:
template<typename T>class Singleton{public:		static T& GetInstance(){static T s; return s;}protected:	Singleton(){}	Singleton(const Singleton&){}	Singleton& operator=(const Singleton&){}	~Singleton(){}};template<typename T>class Derived : public Singleton<T>{public:	Derived(int _i):i(_i){}	int i;};class Person : public Derived<Person>{public:	Person():Derived<Person>(33){}	void Print(){cout << i << endl;}};int main(){	Person::GetInstance().Print();}
Advertisement
I just tried it, looks nice, still playing around with it. Seeing what i can do before causing it to crash

thanks
So with JD''s code, if i put the GetInstance()
into the constructor, all i have to call is Derived d; ?

Ive tried this and it works, but is there anything wrong with this?
quote:Original post by JD
Here''s a very simple templated singleton...

That is not a singleton. A protected ctor only prevents the Singleton base to be instansiated on its own, but it does not prevent any subtype to be created multiple times.

quote:Original post by johnnyBravo
So with JD''s code, if i put the GetInstance()
into the constructor, all i have to call is Derived d; ?

Ive tried this and it works, but is there anything wrong with this?
Yes, it''s wrong. By declaring Derived d, you are creating a second instance of Derived.

This topic is closed to new replies.

Advertisement