http://GameProgrammer.Com

Programming

GP Mailing List
     Thread Index
     Date Index

ATXGPSIG List
     Thread Index
     Date Index

Google
>

Home

TheGrumpyProgrammer



[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gameprogrammer] Re: problem with singleton



On Wed, 16 Jun 2004 08:57:01 -0400, "Roger D. Vargas"
<roger@ehtsc.co.cu> said:

<snip singleton talk>

> What would be the best way to implement it but using a pointer for the
> instance?

Using a pointer?  I'm not sure why you need to use a pointer instead of
just a simple object, but it should be the same basic principle.  We
just need to use a smart pointer (although auto_ptr is barely smart)
instead of a plain pointer, in order to ensure that when the variable
goes out of scope, the object is deleted:

(NOTE - UNTESTED CODE)

class ResourceCollection
{
public:
   static ResourceCollection* singleton();
private:
   ResourceCollection() { /* body */ }
   ~ResourceCollection() { /* body */ }

   // NO BODIES to prevent them ever being used.
   ResourceCollection(const ResourceCollection& rhs);
   ResourceCollection& operator=(const ResourceCollection& rhs);
};

//

ResourceCollection* ResourceCollection::singleton()
{
   static std::auto_ptr<ResourceCollection*> mSingleton(new
   ResourceCollection());
   return mSingleton;
}

END

So the first time singleton() is called, the auto_ptr will be
initialized with a new instance of ResourceCollection.  Because the
constructor is private, no-one can create one any other way.  And
because the destructor is private, no-one can accidentally delete one. 
(However, you may need to make the destructor public, as some compilers
don't allow this, Microsoft IIRC.)  It is also useful to define the copy
constructor and assignment operator private, and don't give them bodies,
so then it's an error if anyone anywhere tries to call one (including in
a member function).

As I said, this code is untested, so if anyone can see any problems in
it, please speak up.  And if you're really interested in the issues,
read 'Modern C++ Design' by Alexandrescu.

Dave.
-- 
  Dave Slutzkin
  Melbourne, Australia
  daveslutzkin@fastmail.fm



---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html