tags:

views:

199

answers:

3

I've read some C++ books explaining how it's important to delete new-allocated memory. I have learnt some strategies like encapsuling the created object inside another object where its destructor will be called, etc, etc. However, if we have a singleton used during all the life of a program.. is it "really" important to delete it?

As I said, I have played the "I'm a good software engineer and I always delete my stuff" game. But, someone whom I really respect told me it was useless to delete such an object because, when the program close, the OS will just override that memory part, and, who cares if there are old trash in that part?

What do you guys think :)

Thanks

(Sorry for the english mistakes.. this is not my native language :])

+1  A: 

I think the main reason for dealing with EVERYTHING is so that you can use memory leak checking tools and techniques without worrying about the singletons, etc interfering.

It's a bit like trying to make sure that your compiles are 100% clean, so that new warnings due to newly introduced bad code to go by unnoticed.

So, again, you're managing that memory not to make the OS happy, but to make it easier for you to use tools to find the memory leaks that can hurt you.

Corey Trager
A: 

Its NOT just the memory leak.

Some resources need to be cleaned up:
Because they are limited or would make the service in-efficient etc. And to be honest it is not difficult to do correctly once you know the pattern. It is easy to get lazy initialization and guaranteed destruction.

Things only get complicated if singletons access other singletons in their constructors/destructors so unless you really-really-really need to do it just don't.

If you are in a multi-threaded environment there are technically some gotchas (but gcc compensates) and you can get around them by forcing initialization before starting any threads or using a simple lock (Just do not bother with double checked locking (you can not make it work in the current version of C++)).

See Here:
http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used
http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c

Martin York
I don't know why people mark answers such as this one down. They should at least have the curtesy to say why. What criteria are people using? +1 from me.
Richard Corden
A: 

I think it's important to always clean-up allocated memory.

Say I'm making a game that you just play once then close. So far it's ok to leave some stuff hanging around because it's just overwritten after you close the game. What if in the future I want to add multiple levels to the game? ... or perhaps let the user enter a high score and then play again? If I didn't clean up stuff because "the game just ends" and I don't fix it before making the high score and play-again options... I now have a memory leak that's potentially hard to find.

MrDatabase