Move Semantics in C++

Level 5301 keystrokes

Buffer takes its string with std::move instead of copying it and defines a move constructor. createBuffer() returns a Buffer by value, and the stored text is printed.

C++ code

// Class that holds a string
1class Buffer {
2 string data;
3public:
// Takes s by value and moves it into data, avoiding a second copy
4 Buffer(string s) : data(move(s)) {}
// Move constructor: takes over other's string instead of copying it
// noexcept lets containers such as vector move it safely
5 Buffer(Buffer&& other) noexcept : data(move(other.data)) {}
6
// Returns the string by const reference, without copying
7 const string& get() const { return data; }
8};
9
// Factory function that returns a Buffer by value
10Buffer createBuffer() {
// Since C++17 the returned temporary is built directly in b (no copy or move)
11 return Buffer("Hello from moved buffer!");
12}
13
// Receives the Buffer returned by createBuffer
14Buffer b = createBuffer();
// Prints "Hello from moved buffer!"
15cout << b.get() << endl;

Output

Hello from moved buffer!
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.

  • (× 11
  • )× 11
  • ;× 6
  • {× 5
  • }× 5
  • <× 4
  • :× 3
  • &× 3
  • .× 2
  • "× 2

More C++ examples at level 5

← C++ typing practice