Using the Copy Assignment Operator to copy objects that have raw pointers.
"A copy constructor is a special constructor for a class/struct that is used to make a copy of an existing instance."
The Implicit Copy Constructor
If a copy constructor is not declared, the compiler will use a default one implicitly. The default constructor performs a member-wise copy of the source object. This means that each member is initialized using the corresponding member of the initializer.
Problem: Raw pointers.
If the object contains raw pointers, a member-wise copy may not be appropriate for use. This can cause problems with dangling pointers, double frees, and other undefined behaviour resulting from destructing objects.
Solution: Deep copy.
We explicitly define our own copy constructor when we want to perform a deep copy. That is, instead of copying the pointer, our copy constructor will copy what the pointer points to. When the object gets destructed, it will be deleting the pointer to its own member.
Examples
Copy Semantics and Copy Constructor using SimpleString:
https://github.com/pereiradaniel/CPP_CRASH_COURSE/blob/master/P1C4/simplestring_copy_constructor.cpp Copy Semantics and Copy Assignment using SimpleString:
References
Copy constructors, assignment operators, and exception safe assignment.
14.14 - Introduction to the copy constructor.