Skip to main content
GameDev.net gamedev.net
🔒 Locked

Deriving from a singleton

Started by d000hg Jan 25, 2005 at 9:54 AM 0 replies 1k views
Original Post
d000hg
d000hg
I tried to do this without much thought and got very confused! Is there an easy way to do this or does it need to be bodged. Can one simply derive, oe does another singleton have to be created around the base class?
desertcube
desertcube
OK, here's how I do it:

#include <memory>class non_copyable{protected:	non_copyable() {}	~non_copyable() {}private:	non_copyable(const non_copyable &);	non_copyable & operator=(const non_copyable &);};template <class T>class singleton : non_copyable{public:	static T * Instance()	{		if (!_object.get()) //Not yet created			_object = std::auto_ptr<T>(new T);		return _object.get();	}protected:	singleton() {}	virtual ~singleton() {}	static std::auto_ptr<T> _object; //auto_ptr ensures T is deleted at end};template <class T>std::auto_ptr<T> singleton<T>::_object; //Initilize static variable


Then to make your class a singleton, you just derive from it + a couple friend declarations:

class MyClass : public singleton<MyClass>{public:	friend singleton<MyClass>;	friend std::auto_ptr<MyClass>;	//Stuffprivate:	MyClass() {}	virtual ~MyClass() {}};

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.