Wednesday, July 4, 2012

delete singleton object in C++ !!

Singleton pattern is used to create only one instance of the class for the application. It will be usefull when you need global resource like Server. Creating the singleton is easy and there wont be any problem. But the problem is when to delete the singleton. It depends on the lifetime of the Singleton.

Method to create the Singleton:
single* single::getInstance()
{
    if(ptr==NULL)
    {
        ptr = new single();
    }
    else
    {
        return ptr;
    }
}
If you want to delete the singleton pointer, dont call the delete on the singleton pointer. Better use some static function like deleteInstance similar to getInstance which used to creat the singleton.

Method to delete the Singleton:
single* single::deleteInstance()
{
    delete ptr;
    ptr = NULL;
}

For single threaded environments it is advised to use a local static varible. So there is no need to use the delete operation. It wont be good for multi threaded environments.
Method to create the Singleton:
single* single::getInstance()
{
    static single sObj;
    return &sObj;
}

P.S:  Try to avoid the use of the Singleton as it is a global resource.

1 comment:

Ashwin Deshpande said...

Thanks for the tutorial

Popular Posts