Data Structures in C++ with Kristoffer Hebert
Shallow vs Deep copying
How do shallow and deep copying compare in C++? The difference lies with how pointers are handled in an object. When shallow copying, the new object reuses pointers from old object. This is effective for resource management when working with multiple objects since data values are pointers. When deep-copying an object, the pointer data values are completely copied over to the new object. This prevents unwanted data changes and side effects between mutable objects. Deep copying can be achieved within an object via a copy constructor or overloading the assignment operator.
What is shallow copying?
Nell B Dale describes shallow copying as “An operation that copies one class object to another without copying any pointed-to data” (Dale 368). This is the default assignment operator logic for objects. This is useful when you want multiple copies of an object and data does not change. Since data is referenced via a pointer, this would save on memory usage.
What is deep copying?
Nell B Dale refers to deep copying as “An operation that not only copies one class object to another but also makes copies of any pointed-to data” (Dale 368). Deep copying in C++ is achieved with an object class constructor or via overloading the assignment operator. A copy constructor is a, “A special member function of a class that is implicitly invoked when passing parameters by value, initializing a variable in a declaration and returning an object as the value of a function” (Dale 358). Copy constructors contain the logic to handle data values within an object and get fired when an object gets copied. Another way to deep copy is overloading the assignment operator. This means we change the default logic with our own assignment logic. Use deep copying when you want multiple clones of an object, where data values need to mutate without affecting other objects.
Remember to use shallow copying for immutable objects and deep copying for mutable objects. Doing this will help with resource management of CPU and memory. This greatly increases the performance of your code. Deep copying also prevents the side effects of using pointers, which can be hard to troubleshoot. This will save you headaches when writing C++ programs.
References
Dale, Nell B. C Plus Data Structures; Third Edition. Jones and Bartlett Learning, 2003.
