Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this non-compliant code example, the resources associated with the object pointed to by pst are not recovered in the event that processItem throws an exception, thereby potentially causing a resource leak.

Code Block
bgColor#FFcccc
langcpp
while (moreToDo) {
  SomeType *pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    throw;
  }
  delete pst;
}

...

In this code, the exception handler recovers the resources associated with the object pointed to by pst.

Code Block
bgColor#ccccff
langcpp
while (moreToDo) {
  SomeType *pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    delete pst;
    throw;
  }
  delete pst;
}

...

A better approach would be to employ RAII. This forces every object to 'clean up after itself' in the face of abnormal behavior, preventing the programmer from having to do so. A judicious unique_ptr would free the resource whether an error occurs or not.

Code Block
bgColor#ccccff
langcpp
while (moreToDo) {
  std::unique_ptr<SomeType> pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    throw; // pst automatically freed
  }
  // pst automatically freed
}

...