Show How to Use a Move-Only Heap Buffer in C++, and Defend It
Data Structure DesignModel answerLast 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:
- Why are copy construction and copy assignment deleted? What would the compiler-generated versions do wrong?
- After
IntBuffer b = std::move(a);, what state isain, and what can you safely do with it? - Why are the move operations
noexcept? What changes for astd::vector<IntBuffer>if they are not? - What does
expliciton the constructor prevent? Show a line that compiles without it and fails with it. - Why are
at,sizeandcapacityconst? What happens if aconst IntBuffer&is used to callpush? - 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Example program
The approach is to give each design decision of the class one visible demonstration: exclusive ownership, move-only transfer, exceptions on misuse, and const access.
#include <iostream>
#include <string>
#include <vector>
#include <utility>
// IntBuffer definition goes here (unchanged)
// Returning by value is fine: the result is moved (or elided), never copied.
IntBuffer makeSquares(std::size_t n) {
IntBuffer buf(n);
for (std::size_t i = 0; i < n; ++i) buf.push(static_cast<int>(i * i));
return buf;
}
// Read-only access: take by const reference. Only const members are callable.
void describe(const IntBuffer& b, const std::string& label) {
std::cout << label << ": size=" << b.size()
<< " capacity=" << b.capacity() << '\n';
}
// Taking by value means the caller must hand over ownership with std::move.
std::size_t consume(IntBuffer b) { return b.size(); }
int main() {
// 1. Construction is explicit and allocates the full capacity up front.
IntBuffer a(3);
a.push(10);
a.push(20);
a.push(30);
describe(a, "a"); // size=3 capacity=3
// 2. Failure path one: pushing into a full buffer throws.
try { a.push(40); }
catch (const std::length_error& e) { std::cout << "full: " << e.what() << '\n'; }
// 3. Failure path two: at() is bounds-checked against size(), not capacity().
try { a.at(3); }
catch (const std::out_of_range& e) { std::cout << "range: " << e.what() << '\n'; }
// 4. Ownership transfer. After the move, a is empty but valid.
IntBuffer b = std::move(a);
describe(a, "a after move"); // size=0 capacity=0 (documented by this class)
describe(b, "b"); // size=3 capacity=3
// a.push(1) would now throw length_error (capacity is 0), not crash.
a = makeSquares(4); // a moved-from object may be reassigned
describe(a, "a reassigned");
// 5. Passing ownership to a function.
std::cout << "consumed " << consume(std::move(b)) << " elements\n";
// b is empty again; do not read its elements.
// 6. Storing in a container: construct in place or move in, never copy.
std::vector<IntBuffer> pool;
pool.emplace_back(2); // explicit ctor works with emplace_back
pool.push_back(makeSquares(3)); // rvalue, so it is moved
pool.push_back(std::move(a));
pool[0].push(7);
std::cout << "pool[0].at(0) = " << pool[0].at(0) << '\n';
// Forbidden, so left as comments:
// IntBuffer c = a; // error: copy constructor is deleted
// IntBuffer d(2); d = a; // error: copy assignment is deleted
// IntBuffer e = 5; // error: constructor is explicit
// describe-style function calling p.push(1) on a const IntBuffer& // error: push is non-const
}
Why this is a good example:
- Every public member is used.
- Both exceptions are caught by their specific types.
- No moved-from object is read for element data, only queried for its documented empty state.
- Each comment says why, not just what.
Part 2: The C++ behind it
1. Deleted copies. The class owns a raw int*. The generated copy would copy the pointer value (a shallow copy), leaving two objects that both believe they own the array. Both destructors would delete[] the same block, which is a double free and undefined behavior. Any write through one object would also silently alter the other. This is the rule of three/five: once you write a destructor that releases a resource, you must define or delete the copy and move operations. Deleting copies makes ownership unique and turns a runtime bug into a compile error. The alternative is a deep copy, which is costly and not needed here.
2. Moved-from state. The move operations swap the source's pointer to nullptr and its sizes to 0 with std::exchange. So a is empty with zero capacity. It is safe to destroy (delete[] nullptr is a no-op), assign to, and query with size() and capacity(). at(i) throws out_of_range, and push throws length_error. It is not safe to assume it still has data. This is stronger than the standard's baseline "valid but unspecified", because this class documents the exact state through its implementation.
3. noexcept moves. When std::vector reallocates, it uses std::move_if_noexcept to preserve the strong exception guarantee of push_back. If a move can throw and a copy exists, the vector copies. Here copying is deleted, so a non-noexcept move would still be used, but the strong guarantee would be lost: an exception mid-reallocation could leave elements already moved and unrecoverable. With noexcept, reallocation is safe and cheap, just pointer swaps. The moves here cannot throw because they only assign scalars and pointers. Note that move assignment frees the old array first, then takes the new one, so no failure point sits between the two steps.
4. explicit. It blocks implicit conversion from std::size_t (or int) to IntBuffer. Without it, IntBuffer b = 5; would compile, as would calling void f(IntBuffer); f(10);. Both read like "an integer is a buffer" and hide a heap allocation. With explicit, you must write IntBuffer b(5); or IntBuffer b{5};. The same applies to pool.push_back(5), while emplace_back(5) still works because it does direct initialization.
5. const correctness. at, size and capacity do not modify state, so marking them const lets them be called on const IntBuffer&, which is how read-only parameters are passed. Calling push on a const reference is a compile-time error (the implicit this is const IntBuffer*, which cannot bind to a non-const member function). It is not a runtime failure. This is why describe can accept a const reference safely.
6. Refactoring to the rule of zero. Replace the raw pointer with std::unique_ptr<int[]> (or a std::vector<int>), then remove the destructor and move operations, and let = default or the compiler handle them. Copies stay disabled automatically with unique_ptr, or become deep copies with vector.
The pitfall is that defaulted moves do not reset the plain size_ and capacity_ members. They are copied, so a moved-from object would report a nonzero size while its array is null, and at(0) would dereference null. You would need to either derive size and capacity from the container (for a vector, size() for the count and a stored capacity that must still be handled), or keep a custom move that zeroes the counters. Also note that unique_ptr<int[]>(new int[n]) leaves values uninitialized, though this class only reads below size_, so that is harmless.
Common mistakes
- Reading elements from a moved-from buffer, or assuming
std::moveitself moves anything (it is only a cast). - Writing
IntBuffer c = a;in live code. - Catching
std::exceptioneverywhere instead of the specific types. - Claiming
noexceptmakes the moves faster rather than making container behavior safer. - Saying a thrown exception and undefined behavior are the same thing.