Announcement

Monday, July 12, 2004

Implementing a Well behaved Singleton - 3

Last time I showed an singleton implementation where 'User has to manage the destruction of Singleton object'. (the part-2 is here). In this part, lets see how to improve on that.

class FooSingleton
{
public:
~FooSingleton(void);
static FooSingleton& GetFooObj(void);

private :
FooSingleton(void);
private :
int m_var;
};

FooSingleton&
FooSingleton::GetFooObj(void)
{
static FooSingleton fooObj;

return(fooObj);
}


If you compare the code from the Part 2 and this code, there are small difference.
1. GetFooObj function is now returning a Reference to FooSingleton and not a pointer. So chances of user, copying and deleting this pointer are less.
2. There is no global FooSingleton pointer. The GetFooObj function is now using a function static instance of FooSingleton (fooObj)


The result is
1. when fooObj is created on the first call to GetFooObj().
2. Every subsequent calls same instance is returned.
3. Since this is a static object, compiler manages the destruction of the object. User don't have to worry about destructing the singleton.
4. Singleton object creation sequence is now predictable. So if some other global/static object is dependent on existence of FooSingleton instance, GetFooObj() function will create it at appropriate time.


THIS IS GOOD. Most the problems with previous implementations are taken care off. However, the destruction sequence is still not predictable. And that is topic of next entry in the series.

No comments: