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
Loading...
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
Loading...
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
Loading...
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 *this to allow chaining (a = b = c).
main.cpp
Loading...
Terminal
Waiting for execution...

05The Copy-and-Swap Idiom (Pro Level)

The modern C++ way to write 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
Loading...
Terminal
Waiting for execution...
← Back to Curriculum