COMP2004 Programming Practice
2002 Summer School

Week 5 Wednesday Tutorial Exercises


  1. Modify your linked list class from Question 2 of last Wednesday's tutorial to be exception safe. Attempt both a weak and strong version if possible.

    As an example, here is the original assignment operator:

    List& List::operator=(const List &o) {
    	if (this == &o)
    		return *this;
    	Node::delete_chain(head);
    	head = Node::deep_copy(o.head);
    	return *this;
    }
    
    This does not meet the weak guarantee since if Node::deep_copy() throws an exception, the List object is not in a consistent state. The simplest consistent state for a linked list is the empty list, so let's change it so it at least does that:
    List& List::operator=(const List &o) {
    	if (this == &o)
    		return *this;
    	Node::delete_chain(head);
    	head = 0;
    	head = Node::deep_copy(o.head);
    	return *this;
    }
    
    Simple enough. Meeting the strong guarantee is a little harder, but we can do it by deleting the old chain of Nodes after the call to Node::deep_copy():
    List& List::operator=(const List &o) {
    	if (this == &o)
    		return *this;
    	Node *old = head;
    	head = Node::deep_copy(o.head);
    	Node::delete_chain(old);
    	return *this;
    }
    
    In this case, if Node::deep_copy() throws an exception, the head variable is never changed, the chain of Nodes isn't deleted, and the exception continues to the calling function.

    Try and do the same for your doubly linked list. The deep_copy part is the trickiest bit to get right...