CodeBlanks Logo Icon CodeBlanks

Summary - Move semantics

Combine std::move and move ctor to write a buffer class.

Summary - Move semantics

In this group you learned move semantics. T&& is an rvalue reference that binds to temporaries, and std::move converts an lvalue to an rvalue.

The move constructor T(T&&) transfers a resource to a new object, and move assignment T& operator=(T&&) transfers to an existing object. The rule of five says to define all five special members together. Now you will consolidate what you learned with two tasks: first an rvalue reference function, then moving with std::move.

Practice Write an rvalue reference function

Define a function named show: its parameter is std::string&& s, its body is std::cout << s;. In main call show("Hello");.

Starter code

main.cpp
#include <iostream>
#include <string>

// Define the show function

int main() {
    // Call the show function
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

void show(std::string&& s) {
    std::cout << s;
}

int main() {
    show("Hello");
    return 0;
}

Expected output

Hello

Practice Move a string with std::move

The starting code has a string a containing "World". Move the content of a into b with std::move and print b with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>
#include <utility>

int main() {
    std::string a = "World";
    // Move the content of a into b and print b

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
#include <utility>

int main() {
    std::string a = "World";
    std::string b = std::move(a);
    std::cout << b;
    return 0;
}

Expected output

World

End of section

You completed move semantics. You can now use the T&& rvalue reference and move with std::move.

With the move constructor and move assignment you transfer resources efficiently. The rule of five and rule of zero tell you when to write special members. The next group covers operator overloading; you will see the move assignment operator there in more detail.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does std::move do?

main.cpp
std::string b = std::move(a);
  • Deletes a
  • Copies a
  • Returns the address of a
  • Converts a to an rvalue Correct answer

Explanation: std::move converts a to an rvalue.

2 rvalue reference parameter

Question
void show(std::string____ s) { std::cout << s; }
Answer
void show(std::string&& s) { std::cout << s; }

Explanation: && is the rvalue reference operator.

All lessons in Intermediate