Exit Wiki

C++ Singleton Pattern - when you only want one instance of a class to exist. Just typed, not checked. But it should show enough of the pattern to make it understandable.

   1 //header file
   2 class someclass
   3 {
   4   public:
   5      someclass* Get()
   6      {
   7         if (TheInstance)
   8           return TheInstance;
   9         else
  10            return new someclass();
  11      }
  12      ~someclass()
  13      {
  14         if (TheInstance == this)
  15            TheInstance = NULL;
  16      }
  17   private:
  18      someclass() { TheInstance = this;}
  19 
  20      static someclass* TheInstance;
  21 };
  22 //source file
  23 someclass* someclass::TheInstance = NULL;
  24 //put in here or linker will hate us

Comments:

Add comments by visiting: CppSingletonPattern/Comments

CppSingletonPattern (last edited 2006-12-08 15:35:31 by RyanWilcox)