Monday, June 11, 2007

Unique instance creator using templates C++

I am presenting an idea to create a unique instance of an object using templates.. This is very similar to Singleton design pattern..
The code may be look like this

class UniqueFactory

{

private :

   UniqueFactory()
   {
   }
public :

   static T * Instance()
   { 
        static T* ptr = new T();
        return ptr;
   }
};
So it will give the same instance of the object always.. For example
int *pInst = UniqueFactory<int>::Instance();
*pInst = 11;
pInst = UniqueFactory<int>::Instance();
*pInst , points to the same unique instance.
Another example is ( UserData can be any struct or class etc. )
UserData *pData = UniqueFactory<UserData>::Instance();
Hopes you may like it..!!

3 comments:

msnkd said...

:)

Sarath said...

KD,I am wondering why you went for a dynamic memory allocation strategystatic T* ptr = new T();static T obj;You can either return by reference or by pointer. So we can reduce the allocation overhead no?(I know it\'s not a big deal)

msnkd said...

Sarath , Because If use static object and when i return an object ,  while returning it creates anothercopy and will create a new object.. So it will loss the uniquenesss. understood ?