Move Semantics

Copying a string duplicates its text; moving it just hands the text over and leaves the source empty.

C++ · beginner · 7 min · 9 steps · free

What you'll learn

move_semantics.cpp

#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

int main() {
    string big = "a long piece of text that lives on the heap";
    string copied = big;              // copy: both have their own text
    string moved = move(big);         // move: moved takes the text; big is left empty
    vector<string> list;
    list.push_back(move(copied));     // moved into the vector, no copy made
    cout << big.size() << " " << moved.size() << " " << list[0].size() << endl;
    return 0;
}

Step by step

  1. C++ enters int main().
  2. big is created on the stack with the value "a long piece of text that lives on the heap".
  3. A copy: copied gets its own duplicate of the text.
  4. move: moved takes big's text; big is left empty.
  5. list is created on the stack with the value [].
  6. Moved into the vector without copying the text.
  7. It prints 0 43 43.
  8. The method returns 0.
  9. 0 43 43.

Common mistakes

Best practices

Key takeaways

Check yourself

Is move cheaper than copy for a long string?

Answer: Yes. No text is duplicated.

Can you use big after moving from it?

Answer: Yes, but treat it as empty. Valid but unspecified (empty in practice).

·

More in Memory and Ownership