Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Destructor and Purge Member Function

Program gif gives the code for the destructor and the Purge member function of the LinkedList<T> class. In the general case, when the destructor is invoked, we cannot expect the list to be empty. Therefore, it is the responsibility of the destructor to first release any ListElement<T>s which have been allocated and linked into the list. And this is precisely what the Purge member function does.

   program3560
Program: LinkedList<T> Class Destructor and Purge Member Function Definitions

The main loop of the Purge function simply traverses all the elements of linked list, deleting each of them one-by-one. Note that the body of the loop has been carefully written so as to determine the new value of head, before deleting the current list element. E.g., the following loop body is the wrong way to do it:

while (head != 0)
{
    delete head;
    head = head->next; // Wrong.  Don't do this.
}
The problem with the code fragment above is that the head pointer is dereferenced after the object to which it points has been deleted. While this code might actually work fortuitously for some compilers on some machines under some operating systems, it is invalid and illegal.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.