Copying collection classes, Copying reference-based collection classes – HP Integrity NonStop J-Series User Manual
Page 103

Click on the banner to return to the user guide home page.
©Copyright 1996 Rogue Wave Software
Copying Collection Classes
Copying classes is a common software procedure. It happens every time a copy constructor is applied,
or whenever a process needs a copy to work on. Copying value-based collection classes is
straightforward. But special considerations arise in copying reference-based classes, and we deal with
them here.
Copying Reference-based Collection Classes
What happens when you make a copy of a reference-based collection class, or any class that references
another object, for that matter? It depends which of the two general approaches you choose: shallow
copying or deep copying.
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 has the same members as the old Set, and shares
objects with the old Set through pointers. Shallow copies are sometimes said to use reference
semantics.
The copy constructors of all reference-based Rogue Wave collection classes make shallow
copies.
1.
A deep copy of an object is a new object with entirely new instance variables; it does not share
objects with the old. For example, a deep copy of a Set not only makes a new Set, but also inserts
items that are copies of the old items. In a true deep copy, this copying is done recursively. Deep
copies are sometimes said to use value semantics.
2.
Note that some reference-based collection classes have a copy() member function that returns a new
object with entirely new instance variables. This copying is not done recursively, and the new instance
variables are shallow copies of the old instance variables.
Here's a graphical example of the differences between shallow and deep copies. Imagine
Bag
, an
unordered collection class of objects with duplicates allowed, that looks like this before a copy :