Modern C++20 Features · 9 min read · Intermediate
Move Semantics & std::move
Transfer ownership of strings and vectors in O(1) without deep copying using std::move and rvalue references (T&&).
What you'll learn
- Understand why moving a vector transfers its internal pointer instead of copying elements
- Use std::move() when transferring ownership of a local variable
- Avoid using a moved-from object without reassigning it first
Copying a std::vector with 1 million elements allocates and copies 1 million items. Moving it with std::move() simply transfers ownership of the underlying heap pointer in $O(1)$ time with zero allocations.
Fill-in-the-Blank Exercise
Transfer Ownership with std::move
Move title into the vector without copying the string buffer.
std::string title = "Modern C++";
std::vector<std::string> items;
items.push_back(std::());Live Code Lab
C++move_demo.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
Moved into vector: Zero-copy transfer Original size now: 0
Check Your Understanding
Score: 0 / 1
1. What does std::move(x) actually do?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.