Skip to main content
gamedev.net
🔒 Locked

Singletons

Started by InsaneX 2 replies 400+ views
Original Post
InsaneX
InsaneX
I read the article on Singletons on gamedev (The One: A Singleton Discussion). I understand the necessity for them, but I was having trouble understanding the implementations. Meyer''s Singleton seems simple enough to me, but the nifty counter confused me. I was thinking that this could be enough (I like the idea of a template instead of implementing it as part of the class)
template <typename T> class Singleton
{
     static T* SingletonClass;
     public:

     Singleton(){SingletonClass = new T;}

     ~Singleton(){delete SingletonClass;}

     GetInstance(){return *SingletonClass}

     GetPtrInstance(){return *SingletonClass}
};
This is very similar to the Ogre engine implementation, except by some act of god (confusing code that baffles me) they never allocate the pointer with new, and they never delete it.
wild_pointer
wild_pointer
The whole point of singletons is to enforce only one instance of any given object, not give you a glorified global variable. How does your code do this?

The easiest to understand implementation would probably be


template <class T>
class Singleton
{
public:
static T* Instance()
{
static T inst;
return &inst
}
protected:
Singleton();
Singleton(const T&);
T& operator= (const T&);
};


Note, not threadsafe.



[My site|SGI STL|Bjarne FAQ|C++ FAQ Lite|MSDN|Jargon]
Ripped off from various people

[edited by - wild_pointer on May 15, 2004 5:29:17 PM]
[size=2]
InsaneX
InsaneX
I wouldn't worry about it being thread unsafe, I don't plan on using threads. Also, for the singleton in your post, can you just put
Singleton<MyClass>;  

without declaring an instance. Unless you implement this into each and every class definition, you can still declare instances of the class. Correct me if any of this is wrong.


[edited by - InsaneX on May 15, 2004 5:10:46 PM]

Topic Locked

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

Sign in to reply to this topic.