I don’t know how many times I’ve thought to myself that I knew it all.  Many times I’ve coded something that I was absolutely sure was correct only to find out I was drastically wrong. 

What’s wrong with this code?

class Object

{

public:

      Object()

            : m_pdata( new BYTE[100] )

      {

      }

      ~Object()

      {

            delete[] m_pdata;

      }

 

private:

      BYTE *m_pdata;

};

 

class Interface

{

public:

      static Object* AllocateObject() { return new Object(); }

      static void DeleteObject( void* pObject )

         { delete pObject; }

};

 

...

 

void Function()

{

      Object* pObject = Interface::AllocateObject();

     

      // do something

 

      Interface::DeleteObject( pObject );

}

 

Answer

It will leak memory. DeleteObject takes in a void* which when deleted will not call the destructor for the Object class and m_pdata leaks.

I made this mistake when I added a new type of object that needed to be allocated from an interface. Then I tried to consolidate the “Delete” functions into a single one (read: "make better"). I didn’t see it when I coded because the classes I tested it with had trivial destructors and freeing the memory was enough. It wasn’t until testers tried more complicated scenarios did the bug manifest itself (read: "made totally worse").