Copy Assignment Operator
When you make one object equal to another.
Use the Copy-and-Swap Idiom to implement this.
Notice that this is simply an operator overload on operator=
!
Copy Constructor vs. Copy Assignment Constructor
In copy assignment operator, you already have your fields initialized. Therefore, you need to do some cleanup. On the other hand, for copy constructor, your fields aren’t initialized, so you don’t need to worry about cleanup.
Some Strategies
Method 1 (the one I will be using)
- check for self assignment:
if(this != &other)
- delete the old resource: delete
this->next
- allocate new resource
this->next = new Object{ *other.next }
- return
*this
Method 2
- Allocate temporary object on STACK: Obj temp(rhs)
- SWAP the internal data with “this”: swap(temp.pointer, this→pointer)
- return
*this
(destructor will clean up the old resources, which got swapped into temp object)