When the dynamically created singleton object should be deleted ? Is it really needed to delete the object explicitly (from destructor) or the not deleted memory will be safely claimed by OS/System once program exits ? What are the consequences if it is not deleted ?
In general it is recommended to destroy the object when the application exits. As mentioned in the comments, most OS's will free the memory when the application terminates, but if you need to clean up for example in the destructor of the singleton, then you need to clean it up yourself (OS cleanup will not call the destructor).
I normally delete it just before my application exits, but this is not always the best solution. I have found that in some cases the singleton is created just to be deleted, or accessed after deletion and gets recreated.
You could use the atexit()
function to register a clean up function when the singleton is created. For example:
static Singleton* s_instance = nullptr;
void cleanupSingleton() {
delete s_instance;
}
class Singleton {
public:
static Singleton* instance() {
if(s_instance == nullptr) {
s_instance = new Singleton();
std::atexit(cleanupSingleton);
}
return s_instance;
}
};
PS: not the best, thread safe singleton example but good enough for the example.
For more information see some references on the atexit()
function:
cplusplus.com or cppreference.com