TGC Codebase Backup



Singleton Example by Dar13

5th Jul 2012 22:44
Summary

This is an example of the singleton programming style in C++.



Description

This is a simple singleton-style class. It isn't as feature-rich or pretty as some other implementations(see Ogre3D's Ogre::Singleton template class) but it gets the job done.

To use, you just use the same format but add your own functions and variables to the class.

For all those who don't know what a singleton is: a singleton is a special type of class that's constructed and managed in such a way as that there is only one instance of the class created at one time, basically the equivalent of a global variable though it has more uses than that.

I'm attaching one of my in-use singleton classes that uses Ogre's Singleton template instead of this simplistic implementation.



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    //Simple implementation of a singleton by Dar13
class foo
{
private:
   //These HAVE to be PRIVATE.
   foo() {}
   foo(const foo& copy) {}
   foo& operator=(const foo& copy) {}
public:
   //VERY IMPORTANT FUNCTION
   static foo& getInstance()
   {
      static foo instance;
      return instance;
   }
   
   //class members go here.
   void printBabble() { printf("BLaH BlaH"); }
private:
   //private class members
};