Sunday, July 04, 2004

Pointer deletion

I sometimes encounter bugs resulting from confusion of ownership of
resources. I'm sure we all do.
One relatively common example and an indicator of this confusion is
multiple attempts to delete a member pointer.

Possible strategies are:

1. NULL out the member pointer after deletion so that a subsequent
attempt to delete the member pointer is a no-op.
(Saves your application from crashing but hides the ownership confusion)

2. Don't NULL out the pointer and leave the potential for an access
violation
(we can now detect any multiple deletion attempts but our application

crashes)

Having considered this quite closely i think this is the best option.

MyClass::~MyClass()
{
  ASSERT( m_pMember );
 
  if(! m_pMember)
  {
 
    LOG("attempt to delete null pointer");
  }
  delete m_pMember;
  m_pMember = NULL;
}

No comments: