星期四, 十二月 14, 2006

Another way to implement a singleton class in C++

A singleton class is very useful when you only need one instance of the class. The other day I took a training, and the speaker introduce an implement of a singleton class. See the codes:
class A{
public:
static A* GetInstance(){
if( !_self ){
_self = new A();
}
return _self;
}

static void Release(){
if( _self) delete _self;
}
...

private:
static A* _self;
A(){};
...
};

A* A::_self = 0;
It's a smart code! But I don't think it's perfect. The above codes need the user to manage the memory. The user must decide when to release the singleton object. Let's consider this scenario. We use a singleton object to refer the whole application object. So, the life time of this singleton object must last from the application begin to run to the application exit. When do the user have the chance to release the object? And the above codes return the singleton object's pointer. I don't think it's a good action. If the user hold more than one pointers of the singleton, and delete one of them, but forget to release others. Later, the user uses some of these left pointers, the application will crash.

I think we can use another way to implement the above singleton class. I don't like say too much :), let's see the codes:
class A{
public:
static A& GetInstance(){
static A _a;

return _a;
}
...

private:
A(){};
...
};

没有评论: