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

Is this a valid singleton

Started by d000hg Nov 17, 2004 at 7:19 AM 5 replies 550+ views
Original Post
d000hg
d000hg
It's going to be used to encapsulate DirectAudio - it seems a singleton is appropriate (but I don't want a discussion over that here). So is this very basic version valid...
class DirectAudio
{
private:
	IDirectMusicPerformance8	*mPerformance;
	IDirectMusicLoader8	*mLoader;
	
	static DirectAudio	*mActiveObject;	//There can be only one
	static unsigned		mCount; //reference counting

	DirectAudio() : mPerformance(0), mLoader(0)
	{
		CoInitialize(NULL);
	}

public:
	~DirectAudio()
	{
		CoUninitialize();
	}
	DirectAudio *GetObject()
	{
	 if(!mActiveObject)mActiveObject=new DirectAudio;
	 ++mCount;
	 return mActiveObject;
	}
	void Release()
	{
	 if(!(--mCount))delete mActiveObject;
	}
};

DirectAudio *DirectAudio::mActiveObject  = 0;
unsigned DirectAudio::mCount  = 0;


I can see problems with security here - when you call GetObject() you can call delete on the result which would screw things up. What should be changed in my class?
Thex0
Thex0
Why not use references? =)
nmi
nmi
Shouldn't
DirectAudio *GetObject()

be static ?
Qw3r7yU10p!
Qw3r7yU10p!
Quote:
Original post by d000hg
I can see problems with security here - when you call GetObject() you can call delete on the result which would screw things up. What should be changed in my class?


C++ doesn't stop programmer stupidity or maliciousness. Even if you return a reference they can take the address and call delete. Return a reference to help prevent genuine mistakes but don't worry too much about security - that's not why you're using a singleton.
d000hg
d000hg
Quote:
Original post by nmi
Shouldn't
DirectAudio *GetObject()

be static ?
Yes ;)
paulecoyote
paulecoyote
You could also use smart pointers to help stablise things, but that's a whole other kettle of herring ;-)
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.

Topic Locked

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

Sign in to reply to this topic.