Tools.h++ Manual
104011 Tandem Computers Incorporated 16-5
16
7 Here’s how we can prove that there are actually two entries in the
collection that point to the same George. Initialize a counter to zero.
8 As before, create an iterator from the collection.
9 Iterate through the collection, item by item, returning a pointer for each
item.
10 Test whether this pointer equals g. That is, test for identity, not just
equality.
11 Delete the objects created in line 4.
The program’s output is “2”, indicating that there are actually two pointers to
the same object “George”.
It is worth looking at what happened in line 4 in more detail. The expression
istr >> sc2;
calls the function
RWvistream& operator>>(RWvistream& str, RWCollectable&
obj);
This function has been written to call the object
obj
’s virtual function
restoreGuts()
. In this case,
obj
is a binary tree and its version of
restoreGuts()
has been written to repeatedly call
RWvistream& operator>>(RWvistream&, RWCollectable*&);
once for each member of the collection
1
. Notice that its second argument is a
reference to a pointer, rather than just a reference. This version of the
overloaded r-shift operator looks at the stream, figures out the kind of object
on the stream, allocates an object of that type off the heap, restores it from the
stream, and finally returns a pointer to it. If this function encounters a
reference to a previous object, it just returns the old address. These pointers
are inserted into the collection by the binary tree’s
restoreGuts()
.
This is why only one instance of “George” was returned.
1. Actually, the Smalltalk collection classes are so similar that they all share the same version of
restoreGuts()
, inherited from
RWCollection
.