The exception-handling mechanism of the Microsoft Foundation Class Library can interrupt normal program flow. Thus, it is very important to keep close track of objects that have been created on the heap so that you can properly dispose of them in case an exception is thrown.
There are two primary methods to do this.
Handle exceptions locally using the TRY and CATCH macros, then destroy all objects with one statement.
Destroy any object in the CATCH block before the exception is thrown outside for further handling.
These two approaches are illustrated below as solutions to the following problematic example code:
void SomeFunc()
{
CPerson* myPerson = new CPerson;
// do something that might throw an exception
myPerson->SomeFunc();
// now destroy the object before exiting
delete myPerson;
}
As written above, myPerson will not be deleted if an exception is thrown by SomeFunc. Execution jumps directly to the innermost exception handler, bypassing the normal function exit and the code that deletes the object. As written above, the pointer to the object goes out of scope when the exception leaves the function, and the memory occupied by the object will never be recovered as long as the program is running. This is known as a memory leak and would be detected by using the memory diagnostics.