Build a Scoped Owner and a Resizable Container from Scratch
Data Structure DesignModel answerLast updated
Implement a move-only smart pointer and a generic dynamic array in C++, exercising RAII, the Rule of Five, placement new, and exception-safe resizing.
Background
Two of the most fundamental building blocks in modern C++ are a scoped ownership wrapper and a growable contiguous container. The standard library ships std::unique_ptr and std::vector, but writing them yourself is the clearest way to demonstrate that you actually understand what those abstractions are doing under the hood.
Part 1 — Scoped Ownership Wrapper
Write a class template ScopedPtr<T> that owns exactly one heap-allocated object and frees it when the wrapper goes out of scope.
Requirements:
- A constructor that accepts a raw pointer.
- A destructor that deletes the owned object.
- Dereference (
*) and member-access (->) operators. - A
release()method that relinquishes ownership, returning the raw pointer and leaving the wrapper empty. - Copying must be forbidden. Moving must transfer ownership and leave the source empty.
Part 2 — Generic Growable Array
Write a class template DynArray<T> that stores elements of type T in a heap-allocated contiguous buffer and grows automatically.
Requirements:
push_back(T value)— appends an element.size()— returns the current element count.operator[]— provides indexed access.- When the buffer is full, allocate a new one with twice the capacity, transfer all existing elements, then release the old buffer.
- Satisfy the Rule of Five: destructor, copy constructor, move constructor, copy assignment, and move assignment must all be handled explicitly.
- The container must accept move-only element types such as
ScopedPtr<T>.
Constraints
- Use
newanddelete(or::operator new/::operator delete) for all memory management — nostd::allocatoror smart-pointer wrappers around the buffer itself. - After completing the implementation, write a short prose explanation (a few sentences is enough) of how your resize logic avoids leaving the container in a broken state when an exception is thrown during the transfer.
Usage Example
ScopedPtr<int> p(new int(10));
DynArray<ScopedPtr<int>> arr;
arr.push_back(std::move(p));
// *arr[0] == 10, p is now empty
Hints
Hint 1
For ScopedPtr, the move constructor and move assignment operator both need to call release() on the source — that single operation atomically hands over the pointer and nulls out the original. In reset(), assign the new pointer to the member variable before deleting the old value, so the object stays consistent even if the destructor of T does something unusual.
Hint 2
DynArray must separate raw memory allocation from object construction. Allocating with new T[cap] default-constructs objects you don't want and fails outright for types with no default constructor. Allocate a raw byte buffer with ::operator new(n * sizeof(T)), construct elements in it with placement new, and tear them down with explicit destructor calls (p[i].~T()) before releasing the buffer.
Hint 3
The resize step should follow a commit-or-rollback pattern: allocate the new buffer and transfer elements entirely before touching the old buffer's state. If a constructor throws partway through the transfer, destroy the partially built elements in the new buffer and free it, then rethrow — leaving the original buffer completely untouched. Consider using std::move_if_noexcept instead of a plain st…
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two classes each illustrate a different layer of C++ resource management.
ScopedPtr is straightforward RAII: one pointer, one owner, deterministic cleanup on destruction. The only design decisions are around the move operations and the ordering inside reset().
DynArray is more involved because a vector has to manage uninitialized storage separately from the objects it contains. Using new T[n] conflates the two and breaks for types with no default constructor. The correct primitive is ::operator new, which hands back raw bytes with no construction side-effects.
Full Implementation
#include <cstddef>
#include <iostream>
#include <utility> // std::move, std::move_if_noexcept, std::swap
// ─────────────────────────── Part 1: ScopedPtr ───────────────────────────
template <typename T>
class ScopedPtr {
public:
ScopedPtr() noexcept : ptr_(nullptr) {}
explicit ScopedPtr(T* p) noexcept : ptr_(p) {}
~ScopedPtr() { delete ptr_; } // delete nullptr is always safe
// No copying
ScopedPtr(const ScopedPtr&) = delete;
ScopedPtr& operator=(const ScopedPtr&) = delete;
// Move transfers ownership
ScopedPtr(ScopedPtr&& other) noexcept : ptr_(other.release()) {}
ScopedPtr& operator=(ScopedPtr&& other) noexcept {
if (this != &other) reset(other.release());
return *this;
}
T& operator*() const { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
T* get() const noexcept { return ptr_; }
explicit operator bool() const noexcept { return ptr_ != nullptr; }
// Relinquish ownership without deleting
T* release() noexcept {
T* p = ptr_;
ptr_ = nullptr;
return p;
}
// Replace the owned pointer, deleting the old one
void reset(T* p = nullptr) noexcept {
T* old = ptr_;
ptr_ = p; // update state first in case ~T re-enters
delete old;
}
private:
T* ptr_;
};
// ─────────────────────────── Part 2: DynArray ────────────────────────────
template <typename T>
class DynArray {
public:
DynArray() noexcept = default;
~DynArray() {
destroy_range(data_, size_);
deallocate(data_);
}
// Copy constructor — only instantiated if actually called,
// so move-only T types still compile as long as you never copy.
DynArray(const DynArray& other)
: data_(allocate(other.size_)), cap_(other.size_) {
std::size_t i = 0;
try {
for (; i < other.size_; ++i)
new (data_ + i) T(other.data_[i]);
} catch (...) {
destroy_range(data_, i);
deallocate(data_);
throw;
}
size_ = other.size_;
}
DynArray(DynArray&& other) noexcept
: data_(other.data_), size_(other.size_), cap_(other.cap_) {
other.data_ = nullptr;
other.size_ = other.cap_ = 0;
}
// Copy-and-swap covers both copy assignment and move assignment.
// An lvalue argument copies into `tmp`; an rvalue moves into `tmp`.
// Either way the subsequent noexcept swap installs the new state.
DynArray& operator=(DynArray tmp) noexcept {
swap(tmp);
return *this;
}
void swap(DynArray& other) noexcept {
std::swap(data_, other.data_);
std::swap(size_, other.size_);
std::swap(cap_, other.cap_);
}
// Takes by value so a single overload handles lvalues, rvalues, and aliasing.
void push_back(T value) {
if (size_ == cap_) grow();
new (data_ + size_) T(std::move(value));
++size_;
}
std::size_t size() const noexcept { return size_; }
std::size_t capacity() const noexcept { return cap_; }
T& operator[](std::size_t i) { return data_[i]; }
const T& operator[](std::size_t i) const { return data_[i]; }
private:
T* data_ = nullptr;
std::size_t size_ = 0;
std::size_t cap_ = 0;
static T* allocate(std::size_t n) {
return n ? static_cast<T*>(::operator new(n * sizeof(T))) : nullptr;
}
static void deallocate(T* p) noexcept { ::operator delete(p); }
static void destroy_range(T* p, std::size_t n) noexcept {
for (std::size_t i = 0; i < n; ++i) p[i].~T();
}
void grow() {
std::size_t new_cap = cap_ == 0 ? 1 : cap_ * 2;
T* new_data = allocate(new_cap); // throws bad_alloc: nothing changed yet
std::size_t i = 0;
try {
for (; i < size_; ++i)
new (new_data + i) T(std::move_if_noexcept(data_[i]));
} catch (...) {
destroy_range(new_data, i); // undo partial construction
deallocate(new_data);
throw; // old buffer is still intact
}
// Past this point every operation is noexcept — safe to commit.
destroy_range(data_, size_);
deallocate(data_);
data_ = new_data;
cap_ = new_cap;
}
};
// ─────────────────────────── Smoke test ──────────────────────────────────
int main() {
ScopedPtr<int> p(new int(10));
DynArray<ScopedPtr<int>> arr;
arr.push_back(std::move(p));
std::cout << *arr[0] << "\n"; // 10
std::cout << (p ? "still owned" : "empty") << "\n"; // empty
}
Why Each Piece Is Correct
Single ownership in ScopedPtr. Every move goes through release(), which atomically hands over the raw pointer and zeroes the source. Two ScopedPtr instances can therefore never hold the same address simultaneously. In reset(), the member is updated to the new value before the old object is deleted; if ~T somehow causes re-entry, the wrapper is already in a valid state.
Rule of Five in DynArray. The destructor, copy constructor, and move constructor are all explicit. The single by-value operator= covers both copy and move assignment through copy-and-swap, and self-assignment is safe automatically because the swap happens after the argument is fully constructed.
Move-only element support. Member functions of a class template are only instantiated when called. DynArray<ScopedPtr<int>> compiles and works correctly as long as you never invoke the copy constructor or copy assignment of DynArray itself.
Exception Safety During Resize
grow() uses a work-on-the-side, then commit strategy:
- Allocate the new buffer. If
::operator newthrowsstd::bad_alloc, the function exits immediately and the array is completely unchanged. - Transfer elements one by one into the new buffer. If a constructor throws partway through, the
catchblock destroys every element already placed in the new buffer, frees it, and rethrows. The original buffer and thesize_/cap_members have not been touched, so the array is still valid. - Only after the full transfer succeeds do we destroy the old elements and free the old buffer — both of which are
noexceptoperations. This is the commit point, and nothing after it can fail.
std::move_if_noexcept adds one extra layer of safety. If a type's move constructor might throw but a copy constructor exists, move_if_noexcept copies instead. That means step 2 can be rolled back cleanly because the originals are still intact — giving the strong guarantee (on failure the array looks exactly as it did before the call). For move-only types there is no copy fallback, so the best achievable guarantee drops to basic (the array remains valid and leak-free, but may have lost some elements if a move throws — an unusual situation for well-written move constructors).
Common Mistakes
- Using
new T[n]for the buffer — breaks for non-default-constructible types and constructs objects at the wrong time. - Forgetting to null out
ptr_inrelease()— leaves two live pointers to the same object. - Destroying old elements before confirming the transfer succeeded — causes a double-free or lost data on exception.
- Implementing copy and move assignment as separate functions rather than copy-and-swap — subtle self-assignment bugs and duplicated logic.