Module 16: C++ Copy and Move Semantics
- First read this page, then start the module with the GitHub classroom link below.
- Github Classroom Link: https://classroom.github.com/a/Sn7O18nH
Learning Objectives:
- Understand the difference between copy and move semantics in C++.
- Learn how to define and use copy constructors, copy assignment operators, move constructors, and move assignment operators.
- Understand the impact of these semantics on performance and memory management.
Exercise 1: Implementing Copy Constructor
Learn how copy constructors work and when they are invoked.
- In the
exercise1folder of your GitHub repository, edit the fileBox.cppand implement a copy constructor in the classBoxwith:- A copy constructor that performs a deep copy.
- Review the code in the file
main.cpp. - Run make.
- Execute the program
main. - Copy the output into the
README.mdfile and give a brief explanation as to what happened.
Exercise 2: Copy Assignment Operator
Understand how to implement the copy assignment operator.
- In the
exercise2folder of your GitHub repository, edit the fileBox.cppand implement the copy assignment operator for theBoxclass:- Ensure that existing resources are cleaned up before performing a deep copy.
- Handle self-assignment correctly.
- Review the code in the file
main.cpp. - Run make.
- Execute the program
main. - Copy the output into the
README.mdfile and give a brief explanation as to what happened.
Exercise 3: Understanding Move Constructor
Explore how move constructors allow efficient resource transfer.
- In the
exercise3folder of your GitHub repository, edit the fileBox.cppand implement a move constructor to theBoxclass:- Transfer ownership of the dynamically allocated
intfrom the source object to the target object. - Set the source object’s pointer to
nullptr.
- Transfer ownership of the dynamically allocated
- Review the code in the file
main.cpp. - Run make.
- Execute the program
main. - Copy the output into the
README.mdfile and give a brief explanation as to what happened.
Exercise 4: Move Assignment Operator
Explore the move assignment operator and resource transfer.
- In the
exercise4folder of your GitHub repository, edit the fileBox.cppand implement a move assignment operator to theBoxclass:- Release any existing resources of the target object.
- Transfer ownership of resources from the source object.
- Leave the source object in a valid state.
- Review the code in the file
main.cpp. - Run make.
- Execute the program
main. - Copy the output into the
README.mdfile and give a brief explanation as to what happened.