Copy vs move semantics
A copy duplicates the data. A move just changes who owns it.
Before you start
When you assign one object to another, what happens? A **copy** duplicates all the data — safe, but potentially expensive if the object owns a big buffer. A **move** transfers ownership — the destination takes the buffer, and the source is left as a valid but empty shell.
Move semantics were added in C++11 because copying a 100 MB string just to pass it to a function is wasteful when the caller was going to throw its copy away anyway.
This lesson shows a copy duplicating a heap buffer and a move stealing one, so you can see why std::move can make a big-object pipeline dramatically faster with no logic changes.
Stack
Heap
the characters — the expensive partCopying the 24-byte stack object is trivial. Copying the 38 characters is the real cost.
Step 1 of 6. One string, one heap buffer. `a` is a small object on the stack — a pointer, a length and a capacity. The characters themselves are too long to store inline, so they live in a heap buffer. This split is what makes copy and move behave so differently. The stack part is cheap; the heap part is not.
Step 01 / 06
One string, one heap buffer
a is a small object on the stack — a pointer, a length and a capacity. The characters themselves are too long to store inline, so they live in a heap buffer.
This split is what makes copy and move behave so differently. The stack part is cheap; the heap part is not.
#include <string>#include <utility>#include <vector>int main() { std::string a = "a long string that will not fit inline"; std::string b = a; // copy: new buffer, bytes duplicated std::string c = std::move(a); // move: buffer handed over // a is now valid but unspecified — do not read it, only reassign it a = "safe again"; std::vector<std::string> v; v.push_back(std::move(c)); // move into the container return 0;}