GCO4020/CSC428 - Advanced Object Oriented Techniques In C++
Week 4

 

Topic 7: Reference Counting

Exercises


Synopsis


Exercise 1

As well as automatically reclaiming memory, the auto_ptr class also provides features which reduce the chance that two or more auto_ptr's will end up pointing to the same piece of memory. Describe those features and how auto_ptr implements them.


Exercise 2

Given that RefCount::Ptr() does nothing but provide unrestricted access to the pointer (myPtr) being guarded by a RefCount object, suggest a reason why myPtr shouldn't just be made public and accessed directly?

There is a sample solution for Exercise 2.


Exercise 3

  1. Specializing the RefCount::Clone() member function, for RefCount<char> solves the problem of cloning reference-counted char* strings, but is insufficient in the general case. Explain why.  
     

  2. Suggest a general solution to the problem of reference counting pointers which must sometimes point at individual objects and sometimes at the start of object arrays?

There is a sample solution for Exercise 3.


Exercise 4

  1. The dereferencing operators provided by RefCountedPointerTo could be used to circumvent the reference counting mechanism. Explain how this might occur and what the consequences might be.  
     

  2. Suggest a means of reducing this hazard presented by the dereferencing operators.

There is a sample solution for Exercise 4.


Exercise 5

The definition of RefCount::Incr() as a const member function implies that a const RefCount should never be declared, since an Incr() on it would be permitted by the compiler but would result in undefined behaviour. Explain why it is reasonable to assume that a const RefCount will never be required in a program.

There is a sample solution for Exercise 5.


Exercise 6

The preliminary check for "assignment to self" in RefCountedPtrTo::operator= is not simply an optimization for efficiency (although it does have that effect). Explain why the check is essential to the correct behaviour of the assignment operation.

There is a sample solution for Exercise 6.


Exercise 7

Explain in your own words why special cyclic reference-counted data structures are not automatically garbage collected when their head pointer is destroyed.

 


This material is part of the GCO4020/CSC428 - Advanced Object Oriented Techniques In C++ course.
Copyright © Damian Conway, 1997. All rights reserved.

Last updated: Fri Feb 18 11:17:28 2000