C++ Programming: Objects, RAII and the STL ยท Memory and Ownership

Move Semantics

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

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.