C++ Foundations·Practice drills 10

Drill 24: Make it smaller — Move semantics

Write a smaller version of the example that keeps the core idea.

Intermediate 5 min read Lesson 242 of 300 Challenge included
What you will be able to do
  • Write a smaller version of the example that keeps the core idea.

Practice task

Write a smaller version of the example that keeps the core idea.

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

Write a smaller version of the example that keeps the core idea.

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 242 of 300 · 0% of course