Tools.h++ Manual

104011 Tandem Computers Incorporated 12-3
12
Shallow versus deep copies
Reference-based collections
What happens when you make a copy of a reference-based collection? It turns
out that this is a more general issue: it doesn't just affect collection classes, but
any class that references another object. Hence, if the type of object that a
value-based collection is collecting is an address, then this issue will arise there
too.
There are two general approaches: shallow copying and deep copying.
1. A shallow copy of an object is a new object whose instance variables are
identical to the old object. For example, a shallow copy of a
Set
will have
the same members as the old set. The new
Set
will share objects with the
old
Set
(through pointers). Shallow copies are sometimes referred to as
using reference semantics.
2. A deep copy of an object will make a copy with entirely new instance
variables. The new object will not share objects with the old object. For
example, a deep copy of a Set would not only make a new set, but the items
inserted into it would also be copies of the old items. In a true deep copy,
this copying is done recursively. Deep copies are sometimes referred to as
using value semantics.
Note – The copy constructors of all reference-based Tools.h++ collection classes
make shallow copies.
Some reference-based collection classes have a
copy()
member function that
will return a new object with entirely new instance variables, although this
copying is not done recursively (that is, the new instance variables are shallow
copies of the old instance variables).
Here are graphical examples. Imagine a
Bag
(an unordered collection of
objects with duplicates allowed) that looks like Figure 12-1 on page 4 before a
copy :