Tools.h++ Manual

19-4 104011 Tandem Computers Incorporated
19
RWFile& operator>>(RWFile&, RWCollectable&);
RWvistream& operator>>(RWvistream&, RWCollectable*&);
RWFile& operator>>(RWFile&, RWCollectable*&);
to save and restore the morphology of a class (i.e., the correct relationship
between pointers).
When working with
RWCollectables
, it is useful to understand how these
functions work. Here is a brief description.
When you call one of the l-shift
(<<)
operators for the first time for any
collectable object, an
IdentityDictionary
is created internally. The object’s
address (i.e., "
this
") is put in the table, along with its ordinal position in the
output file (the first, the second, etc.). Once this has been done, a call is made
to the object’s virtual function
saveGuts()
. Because this is a virtual function,
the call will go to the derived class’s definition of
saveGuts()
. As we have
seen, the job of
saveGuts()
is to store the internals of the object. If the object
contains other objects inheriting from
RWCollectable
(as all of the collection
classes do, as well as many other classes), then the object’s
saveGuts()
, if it
has been written correctly, will call
operator<<()
recursively for each of
these objects. Subsequent invocations of
operator<<()
do not create a new
IdentityDictionary
, but do store the object’s address in the already
existing dictionary. If an address is encountered which is identical to a
previously written object’s address, then
saveGuts()
is not called. Instead, a
reference is written that this object is identical to some previous object (say, the
sixth).
When the entire collection has been traversed and the initial call to
saveGuts()
returns, then the
IdentityDictionary
is deleted and the
initial call to
operator<<()
returns.
The function
operator>>()
essentially reverses this process and, when
encountering a reference to an object that has already been created, merely
returns the address of the old object rather than asking the
RWFactory
to
create a new one.
Here is a more sophisticated example of a class that uses these feature:
#include <rw/collect.h>
#include <rw/rwfile.h>
#include <assert.h>