KatInterview

Show How to Use a Move-Only Heap Buffer in C++, and Defend It

Data Structure DesignModel answer
EasyModel answerData Structure Designcppraiimove-semantics

Last updated

Read a move-only C++ class that owns a heap array, write a clean example program that uses it correctly, and explain the ownership, move, noexcept, explicit and const rules behind it.

You are given a small C++ class you have not seen before and asked to write a program that teaches a new teammate how to use it. While you do, you are asked C++ fundamentals questions about why your code compiles and behaves as it does.

Here is the class, a fixed-capacity buffer of int that owns a heap array. Treat it as read-only.

#include <cstddef>
#include <stdexcept>
#include <utility>

class IntBuffer {
public:
    explicit IntBuffer(std::size_t capacity)
        : data_(new int[capacity]), capacity_(capacity), size_(0) {}

    ~IntBuffer() { delete[] data_; }

    IntBuffer(const IntBuffer&) = delete;
    IntBuffer& operator=(const IntBuffer&) = delete;

    IntBuffer(IntBuffer&& other) noexcept
        : data_(std::exchange(other.data_, nullptr)),
          capacity_(std::exchange(other.capacity_, 0)),
          size_(std::exchange(other.size_, 0)) {}

    IntBuffer& operator=(IntBuffer&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            data_ = std::exchange(other.data_, nullptr);
            capacity_ = std::exchange(other.capacity_, 0);
            size_ = std::exchange(other.size_, 0);
        }
        return *this;
    }

    void push(int value) {
        if (size_ == capacity_) throw std::length_error("IntBuffer is full");
        data_[size_++] = value;
    }

    int at(std::size_t index) const {
        if (index >= size_) throw std::out_of_range("IntBuffer index out of range");
        return data_[index];
    }

    std::size_t size() const { return size_; }
    std::size_t capacity() const { return capacity_; }

private:
    int* data_;
    std::size_t capacity_;
    std::size_t size_;
};

Rules

  • Do not modify the class for Part 1.
  • Your program must compile and run with no undefined behavior. Code that is meant to fail to compile may appear only in comments.
  • Standard headers such as <iostream> and <vector> are available. Assume C++14 or later.

Part 1: Write the usage example

Write a short program (main() plus small helpers if you like) that:

  • Exercises every public member.
  • Triggers and handles each failure the class reports.
  • Shows how to pass, return and store buffers without copying them.
  • Never relies on a moved-from buffer still holding its data.
  • Uses comments to explain why each usage is correct or forbidden.

Part 2: Explain the C++ behind it

Be ready to answer:

  1. Why are copy construction and copy assignment deleted? What would the compiler-generated versions do wrong?
  2. After IntBuffer b = std::move(a);, what state is a in, and what can you safely do with it?
  3. Why are the move operations noexcept? What changes for a std::vector<IntBuffer> if they are not?
  4. What does explicit on the constructor prevent? Show a line that compiles without it and fails with it.
  5. Why are at, size and capacity const? What happens if a const IntBuffer& is used to call push?
  6. If you could change the class, how would you get rid of the hand-written destructor and move operations, and what new pitfall would you need to watch?

Hints

Hint 1

Separate the three kinds of failure: things the compiler rejects (copying, implicit conversion, calling push on const), things the class reports with exceptions (full buffer, bad index), and things that would be undefined behavior (which your example must avoid).

Hint 2

This class explicitly resets the source of a move to a null pointer with size 0 and capacity 0. Your example can rely on that documented state, for instance by checking size() == 0, and can assign a fresh buffer to the moved-from object.

Hint 3

For the refactoring question, think about replacing the raw pointer with std::unique_ptr<int[]> or std::vector<int>. Then ask what happens to the plain size_ and capacity_ integers when the defaulted move operations run.