开发者

Releasing attributes' memory of singleton class

开发者 https://www.devze.com 2023-04-02 12:06 出处:网络
Considering the following Singleton class, I am not releasing memory in the 开发者_开发百科destructor. But the instance of this class will remain the life-time of the program as most of the single-ton

Considering the following Singleton class, I am not releasing memory in the 开发者_开发百科destructor. But the instance of this class will remain the life-time of the program as most of the single-ton class do. Is it really matter to release the attribute's memory other than best practices perception?

class Singleton
{
private:
    Singleton() { pbyte1 = new BYTE[100]; }
    ~Singleton() {};
    BYTE* pbyte1;
    static SingletonInstance* pInstance;

    public:

    static Singleton* GetInstance()
    {
        if( pInstace ) return pInstance; 
        else 
        pInstance = new Singleton();
    }
};


It does matter for debugging. If you run a tool for detecting memory leaks, the leaks caused by this singleton will pollute the output, making it harder to detect real memory leaks.


It depends on the nature of the resources. Usually, the best practice is not to destruct the singleton; destructing the singleton can give rise to order of destructor problems. The exception is if the singleton uses resources which won't be freed by the system (e.g. temporary files); in this case, the "classical" implementation of the instance() function is:

Singleton& Singleton::instance()
{
    static Singleton theOneAndOnly;
    return theOneAndOnly;
}

In this case, the destructor of theOneAndOnly will be called during shutdown. For this reason, you must ensure that the singleton is never used in the destructor of a static variable.

By the way, you're implementation is broken as well. It should be:

Singleton& Singleton::instance()
{
    static Singleton* theOneAndOnly = new Singleton;
    return *theOneAndOnly;
}

This is the usual solution.


As Björn said: it matters for debugging.

It matters also for maintenance. The program will change. It will be refactored. If during refactoring a singleton suddenly isn't a singleton anymore, the missing destructor might introduce real leaks. Additionally, in the future the object might need more than memory (e.g. db handles). Not returning them on closing the program is a true error.

So if you want a best practice: Every destructor should return the resources the object owns. This includes destructors of objects where you could rely on the OS to take them on program shutdown.


If the singleton instance is remaining for the lifetime, then no need to worry about releasing the class resources. When the program terminates, they will vanish (I don't mean automatic delete).

The best practice is to declare the class objects as automatic when the size is fixed.

class SingleTon
{
//...
  BYTE pbyte1[100];
//...
};
0

精彩评论

暂无评论...
验证码 换一张
取 消