|
|
|
|
|
|
|
while ( !IsEmpty() )
// Invariant (prior to test):
// All nodes before current first node in list
// have been deallocated
DeleteTop(temp);
} |
|
|
|
|
|
|
|
|
The copy-constructor is harder to write. Before we look at it, we must stress the importance of providing a copy-constructor whenever we also provide a destructor. Pretend that OrdList doesn't have a copy-constructor, and suppose that a client passes a class object to a function using pass-by-value. (Remember that passing a parameter by value sends a copy of the value of the actual parameter to the function.) Within the function, the formal parameter is initialized to be a copy of the caller's class object, including the caller's value of the private variable head. At this point, both the actual parameter and the formal parameter are pointing to the same dynamic linked list. When the client function returns, the class destructor is invoked for the formal parameter, destroying the only copy of the linked list. Upon return from the function, the caller's linked list has disappeared! |
|
|
|
|
|
|
|
|
By providing a copy-constructor, we ensure deep copying of an actual parameter to a formal parameter whenever pass-by-value occurs. The implementation of the copy-constructor, shown below, employs a commonly used algorithm for creating a new linked list as a copy of another. |
|
|
|
|
|
|
|
|
OrdList::OrdList( const OrdList& otherList )
// Copy-constructor
// Postcondition:
// IF otherList.head == NULL (i.e., the other list is empty)
// head == NULL
// ELSE
// head points to a new linked list that is a copy of
// the linked list pointed to by otherList.head
{
NodePtr fromPtr; // Pointer into list being copied from
NodePtr toPtr; // Pointer into new list being built
if (otherList.head == NULL)
{
head = NULL;
return;
}
|
|
|
|
|
|