简体   繁体   中英

Static allocated memory release

I've a singleton class as follows:

class myClass
{
public:
    static myClass* getInstance();
    ~myClass();

private:
    static myClass* m_instance;
protected:
    myClass();
};

and for above class definition is:

myClass* myClass::m_instance = 0;

myClass::myClass() 
{
}

myClass::~myClass() 
{
}

myClass* myClass::getInstance() 
{
   if(m_instance == 0)
     m_instance = new myClass;
   return m_instance;
}

As it's known, once memory is allocated with new , it ought to be released to heap to prevent memory leak. In my case I have allocated memory which is not concerned with destructor due to that it's static. So, how can I release memory allocated? Am I supposed to free it at all? Won't that lead to a memory leak as I have other classes' objects that function in the main() as well?

PS: the object returned by getInstance() method exists in the main() until the shutdown of an application.

You could use a smart pointer instead of a raw pointer and then you don't have to think about it :)

If you are using C++11 you can use unique_ptr . If you are using an older compiler than use auto_ptr .

Also, the code above is not thread safe.

If the object persists until program shutdown, you don't necessarily have to free it. However, you may want to release resources (files, sockets, database connections, etc.) held by the singleton at shutdown time; you can do this with a static "deinitialization" function called during normal program shutdown.

By the way, the way you initialize the singleton is not threadsafe. You may want to use a threadsafe singleton instead.

In this case you would have to delete your object using the pointer in your main (or wherever you have access to it before it goes out of scope).

Something like:

int main()
{
    myClass* inst = myClass::getInstance();
    // ... do something with it here
    delete inst;
}

Although this is generally a bad practice, because you should not have a new/delete "running wild" anywhere in your program. It's better to stick to the RAII concept and bind your heap-stored memory with some objects on stack using constructors and destructors.

In this specific case - instead of using "new mClass" in "getInstance()" you could just declare m_instance as static.

myClass& myClass::getInstance()
{
    static myClass instance;
    return instance;
}

This way you don't have to release any memory at all since it will be auto released with all other statics in your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM