C++ Foundations·Practice drills 10

Drill 25: Explain each line — Move semantics

Explain what each line of the example does.

Intermediate 5 min read Lesson 252 of 300 Challenge included
What you will be able to do
  • Explain what each line of the example does.

Practice task

Explain what each line of the example does.

buffer.cppC++
#include <cstddef>
#include <iostream>
#include <utility>
#include <vector>

class Buffer {
public:
    explicit Buffer(std::vector<int> data) : data_(std::move(data)) {}

    Buffer(Buffer&& other) noexcept : data_(std::move(other.data_)) {}

    Buffer& operator=(Buffer&& other) noexcept {
        data_ = std::move(other.data_);
        return *this;
    }

    std::size_t size() const { return data_.size(); }

private:
    std::vector<int> data_;
};

Buffer make_buffer() {
    std::vector<int> values{1, 2, 3, 4};
    return Buffer{std::move(values)};
}

int main() {
    Buffer a = make_buffer();
    Buffer b = std::move(a);
    std::cout << b.size() << "\n";
}
Your turn

Write your answer

Easy

Explain what each line of the example does.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 252 of 300 · 0% of course