Singleton Help

Started by
13 comments, last by ganbree 15 years, 8 months ago
Well I have three options to handle the inability to hold multiple graphics objects.

> Do nothing, have unobvious crashes providing no information and leaving the user unaware as to why the engine is crashing when they add the input object for the first time, (or so they think).

> Throw an exception in the constructor. So this is a singleton without global access.

> Use a singleton.

After a rethought I'm leaning towards number two, because I've forgotten why I thought I needed global access now. Might have been be something to do with the massive indirection chains I'm noticing in my code.
Advertisement
So my new Singleton implementation isn't strictly a singleton, as it doesn't provide global access.

template <class T> class CJT::Singleton{private:	static bool Created;	static CCriticalSection CriticalSection;public:	Singleton( void )	{		// Enter critical section, modifys static objects		CriticalSection.Enter();		// Check that the singleton hasn't already been created		if(! Created)		{			// Make sure the critical section is not orphoned			CriticalSection.Leave();			// Throw an exception			throw Exceptions::DuplicateSingleton();		}		// Leave critical section		CriticalSection.Leave();	}	~Singleton( )	{		// Enter critical section, modifys static objects		CriticalSection.Enter();		// Check that the singleton has been created		if( Created )		{			// Make sure the critical section is not orphoned			CriticalSection.Leave();			// Throw an exception			throw Exceptions::InvalidSingleton();		}		// Leave critical section		CriticalSection.Leave();	}};


Thus the name is a little confusing, any ideas as to a better one? I've swapped to this mostly because I like RAII, and using the classic singleton stops me for using it.
Singletons without global access are great for abstracting hardware. As for name... *shrug*. "PrivateSingleton"? BTW, your implementation there seems to have a couple of bugs... Created is accessed but never set, and the if-clauses in the constructor and the destructor seem to be switched.
Why not just use static functionality, instead of making a class at all?
Yeh, I noticed that, slightly embarrassing mistakes those. Got those fixed.

As to using a class instead of using statics, RAII and implicit destruction.

For naming it I've gone for "GlobalSingleton" for the classic singleton with global access and "LocalSingleton" for the half-singleton thing, fairly logical.

This topic is closed to new replies.

Advertisement