Last time I wrote a piece about why initializing variables in C++ is very important. This time a short one about why destroying variables can be hell. Again for C++, since most other languages (Pascal excluded) do it for you.
Here’s the problem I’ve been facing lately: I work in C++ some of the time, and I try to delete every piece of memory I allocate. Sometimes, mostly by accident I do it twice. C++ doesn’t like this and it warns me with dbheap errors. Which is fine. By now I sorta understand what all of these errors mean.
So to prevent this I created a SafeDelete template. This is to take care of safely deleting any object and making sure it won’t happen twice. The template looks something like this:
void SafeDelete(PointerType*& pointer)
if (pointer != NULL)
pointer = NULL;
I’m not shy on publishing this code, because I think it will help you. Especially when you are a beginning programmer. Deleting objects is now as simple as calling SafeDelete(object).