In this lecture, we'll introduce the idea of shallow copies vs. deep copies, its connection to dynamic resource management, and the way these concepts are realized specifically in C++ via the Big Three.
1: Warm Up Exercise
1.1
1.1 Exercise: Warm Up
Consider the code below for the The code also contains a
Go ahead and run the lobster simulation (you can just click "run" to skip all the way to the end). Then, observe the contents of memory and the structure of the two sets. Can you identify any potential problems that might lead to unintuitive behavior? You're welcome to check your solution with this walkthrough video: |
2: The Shallow Copy Problem
2.1
Let's take a look at the built-in copying behavior we get in C++ for compound objects (i.e.
2.1 Exercise: Shallow Copy Problems
Consider the code for
You're welcome to check your solution with this walkthrough video: |
3: Deep Copy Constructors
3.1
The semantically correct way to copy an
3.1 Exercise:
UnsortedIntSet Copy Constructor
Implement a custom copy constructor for
(Hint: Steps 1 and 2 should be done in the member-initializer-list, and 3 uses a loop in the body of the constructor.) The You're welcome to check your solution with this walkthrough video: |
4: Deep Copy Assignment
4.1
Copies are also made when we perform assignment on already-existing objects (as opposed to declaring a completely new object as a copy of another). The key difference is that in this case, the assigned-to object will already have some prior dynamic resources that need to be cleaned up before the deep copy is made. Additionally, to implement the deep copy properly in C++, we can conveniently overload the
4.1 Exercise:
UnsortedIntSet Assignment Operator
Implement a custom copy constructor for
The You're welcome to check your solution with this walkthrough video: |
5: The Big Three
5.1
Finally, let's take a look at the connection between dynamic resource management with destructors and the necessity for a deep copy via a custom copy constructor and assignment operator. Affectionately, these are called "the big three" - and it turns out that they come as a package deal. Here's some more details:
5.1 Exercise: The Big Three
Determine what is printed by the following code. To do this, you'll need to think about where each of the Big Three are used by the code in the main program. Record your prediction in the box at the right. You can use the simulation to double check your answer. Note: The run button in the simulation automatically pauses at the end of main. If you want to see all the output, including the destructors that run as main ends, you can click "run", "step", then "run" again.
You're welcome to check your solution with this walkthrough video: |