Making a Shallow Copy
The copy constructor and assignment operator for a handle make shallow copies. A copy of a handle still refers to the original body, and methods that affect data operate on the original body.
Consider the following C++ code sample:
USAddress address1;
address1.setName("Robert Smith");
address1.setAddress("1234 Main Street");
USAddress address2 = address1; //1
address2.setName("Louise Jones");
address2.setAddress("567 Elm Court");
std::cout << "address1 is "
<< address1.getName() << " at "
<< address1.getAddress() << std::endl;
The code sample produces the output below:
address1 is Louise Jones at 567 Elm Court
Because USAddress is a handle class, line //1 makes address2 a handle to the body referenced by address1. Because address1 and address2 share a body, calls to setName and setAddress on either handle change the data for both handles.
Figure 3 illustrates the relationship between address1 and address2:
Figure 3 – Copy construction of handle-body classes