C++ Copy Assignment and Move Assignment
This is the next part after default, copy, and move constructors.
Series navigation: Previous: Default constructor, copy constructor, move constructor | Next: The Rule of Three / Rule of Five
The important difference:
- Constructor: creates a new object.
- Assignment operator: changes an object that already exists.
Constructor vs assignment
Move has the same idea:
Copy assignment
Copy assignment copies the value from one existing object into another existing object.
Typical signature:
Why return Robot&?
So chained assignment can work:
Why const Robot&?
constmeans we should not modify the source object.&avoids copying the object before assignment.
Move assignment
Move assignment takes resources from another existing object.
Typical signature:
Robot&& can bind to temporary objects and to objects passed through
std::move.
After this, b is still alive and valid, but its value may be empty or changed.
Self assignment
This can happen:
For simple classes that use std::string, std::vector, and smart pointers,
the compiler-generated assignment operators usually handle this.
For classes that manually own raw memory, you must be careful not to delete the resource before copying from it.
Full example
Expected idea
This line creates a new object, so it uses the copy constructor:
This line changes an existing object, so it uses copy assignment:
This line changes an existing object using move assignment:
std::move(a) does not destroy a. It only allows the move assignment operator
to take resources from a.
Rule of thumb
- Use copy constructor when creating a new object from another object.
- Use copy assignment when both objects already exist.
- Use move constructor when creating a new object from a temporary or movable object.
- Use move assignment when the target object already exists and can take resources.
- Prefer compiler-generated copy and move operations when your class only uses standard library members.
Run online
Copy the full example above and run it in the embedded OneCompiler C++ runtime.
Other online compilers: OneCompiler | Compiler Explorer | Wandbox
Run locally
Save the example as main.cpp:
Series navigation: Previous: Default constructor, copy constructor, move constructor | Next: The Rule of Three / Rule of Five