Copy Semantics
Last updated: 1/9/2025
When copying an object in C++ it is sometimes useful to define a copy function instead of using the default, a default copy looks like:
ClassName var2 = var1;This results in a shallow copy where are all of the members of var2 are set to the same value as the members in var1. This can be problematic when var2 uses pointers.
For example, if var2 has a pointer to an array then when you make a copy, var2 and var1 will end up sharing the same array, and if you don't manually delete the data stored at the var2 array then it will result in a memory leak.
This is a shallow copy. This is in contrast to a deep copy.
A deep copy is what you usually want to have happen, it is when two different variables have the same values, but the objects are stored in different places in memory.
To do a copy in a constructor, it looks like:
ClassName& ClassName::ClassName(const &ClassName other){ // Assign all member variables // Allocate memory on the free store // If there is any data on the free store then copy that over element-wise}To do the copy in an assignment, it looks like:
ClassName& ClassName::ClassName(const &ClassName other){ // Assign all member variables // Delete any data that was stored on the free store // Allocate memory onto the freestore // If there is any data on the free store then copy that over element-wise}
The rule of zero and the rule of three
As a general guideline, if you do not need a constructor, then do not implement it and then do not implement any of the other copy functions. The rule of three is if you have a constructor that is not the default then you need to include all of the other copy functions.
See Also
- [[c]]