Destroying Objects A Risky Bussiness

By | March 8, 2007

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:

[code language=’cpp’]template
void SafeDelete(PointerType*& pointer)
{
     if (pointer != NULL)
     {
         delete pointer;
         pointer = NULL;
      }
}[/code]

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).

Leave a Reply