CurriculumAssignment Operator
Assignment Operator
The <strong>Copy Assignment Operator</strong> (<code>operator=</code>) is called when you assign the value of one existing object to another existing object. It is fundamentally different from the Copy Constructor, which is called when a NEW object is created from an existing one.
01Copy Constructor vs Assignment
Rule of thumb: If a NEW object is being created on that line, it's the Copy Constructor. If both objects ALREADY existed before that line, it's the Assignment Operator.
main.cpp
Terminal
Waiting for execution...
02The Danger of Default Assignment
Just like the copy constructor, the default assignment operator does a shallow copy. This is doubly dangerous here: not only do two objects point to the same memory (double free crash), but the original memory of the left object is lost forever (memory leak!).
main.cpp
Terminal
Waiting for execution...
03The Self-Assignment Bug
Before we write the operator, we must understand the self-assignment bug. What happens if someone writes
x = x;? If your operator= blindly deletes its current memory before copying from the other object, it will delete the very memory it needs to copy from!main.cpp
Terminal
Waiting for execution...
04Writing a Custom Operator=
Here are the 4 steps:
1. Check self-assignment.
2. Free OLD memory.
3. Allocate NEW memory and copy data.
4. Return
1. Check self-assignment.
2. Free OLD memory.
3. Allocate NEW memory and copy data.
4. Return
*this to allow chaining (a = b = c).main.cpp
Terminal
Waiting for execution...
05The Copy-and-Swap Idiom (Pro Level)
The modern C++ way to write
Instead of taking the parameter by const reference, you take it by value. This forces the Copy Constructor to do the hard work of copying. Then, you simply swap the pointers!
operator= is the Copy-and-Swap idiom. It is cleaner and completely Exception Safe. Instead of taking the parameter by const reference, you take it by value. This forces the Copy Constructor to do the hard work of copying. Then, you simply swap the pointers!
main.cpp
Terminal
Waiting for execution...
AI Tutor
Like the Copy Constructor, the default assignment operator does a Shallow Copy. If you have heap memory, this causes memory leaks (the old memory is orphaned) AND double-free crashes. You must write a custom operator= to do a Deep Copy.