Modern C++ • C++20 baseline
Copying, Moving, and Value Semantics
Understand when objects duplicate values and when they transfer resources.
Copying creates another value with equivalent state. Moving allows a type to transfer resources from an object that is about to be discarded, often avoiding an expensive allocation. Standard containers and strings already implement these operations; do not write special member functions until the type has a resource or semantic requirement that demands them.
Key points
- Moved-from standard-library objects remain valid but their values may be unspecified.
- The Rule of Zero means letting member types manage their own copy and cleanup behavior.
Example
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string original = "resource-owning value";
std::string moved = std::move(original);
std::cout << moved << '\n';
}
What to expect
The string value is moved into moved; original remains valid but its contents are unspecified.
Practice exercise
Create a type composed only of std::string and std::vector members. Explain why it usually needs no custom destructor or copy operation.
Key idea: Use standard value types and follow the Rule of Zero whenever possible.