Move semantics in C++

Level 4211 keystrokes

std::move lets dest take over the contents of source without copying the strings; afterwards source is empty and dest holds a b c.

C++ code

1vector<string> source = {"a", "b", "c"};
// move casts source to an rvalue, so the move constructor steals its buffer
2vector<string> dest = move(source);
// The moved-from vector is left empty: prints Source size: 0
3cout << "Source size: " << source.size() << endl;
// dest now owns all three elements: prints Dest size: 3
4cout << "Dest size: " << dest.size() << endl;
// Print a b c (auto& avoids copying each string)
5for (auto& s : dest) cout << s << " ";

Output

Source size: 0
Dest size: 3
a b c 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 18
  • "× 12
  • ;× 5
  • (× 4
  • )× 4
  • :× 3
  • ,× 2
  • .× 2
  • =× 2
  • >× 2

More C++ examples at level 4

← C++ typing practice