Copy Semantics and the Rule of Five
Deciding what it means to copy, assign and destroy your own resource-owning types
- name the special member functions the compiler generates and say what each does by default,
- explain the difference between a shallow and a deep copy and why shallow copy of an owning class causes a double free,
- write a correct copy constructor and copy-assignment operator (including the copy-and-swap idiom),
- apply the Rule of Three, the Rule of Five and the Rule of Zero, and use
=defaultand=deleteto control which operations exist.
This topic assumes you already know raw pointers, new/delete and RAII. It is the missing piece that Introduction to Move Semantics quietly depends on: move operations only make sense once you understand copy operations.
1. The special member functions
There is a small set of member functions that the compiler will generate for you if you do not write them. They are called the special member functions. For copy semantics, three of them matter first:
- Destructor
~T()- runs when the object dies; its job is to release whatever the object owns. - Copy constructor
T(const T&)- builds a brand-new object as a copy of an existing one (T b = a;orT b(a);). - Copy-assignment operator
T& operator=(const T&)- replaces the contents of an already-built object with a copy of another (b = a;).
Two more join them in modern C++ (the move operations, which you met in the previous topic): the move constructor T(T&&) and the move-assignment operator T& operator=(T&&). Together these five are the subject of the Rule of Five.
int that copies the value; for a raw pointer that copies the address - not the memory it points at. That single fact is the root of every bug in this topic.