Build a Type-Safe C++ Stack from Raw Storage
Stacks & QueuesModel answerLast updated
Implement a generic, dynamically growing C++ stack using raw memory and placement new, then defend every lifetime, allocation, and call-semantics decision.
Build a Type-Safe C++ Stack from Raw Storage
Design and implement a generic stack in C++ that manages its own memory directly — no std::vector, no std::deque, no other container as a backing store. You control every byte: allocation, object construction, destruction, and deallocation are all yours.
Target this interface exactly:
template <class T>
class Stack {
public:
Stack();
~Stack();
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
Stack(Stack&&) noexcept;
Stack& operator=(Stack&&) noexcept;
void push(const T& value);
void push(T&& value);
template <class... Args>
T& emplace(Args&&... args);
void pop();
T& top();
const T& top() const;
bool empty() const noexcept;
std::size_t size() const noexcept;
};
Behavioral contract
- Calling
toporpopon an empty stack must throwstd::out_of_range. push,emplace,top,pop,empty, andsizeare all amortized O(1); growth is O(n) and happens rarely.- Every stored object must be constructed exactly once and destroyed exactly once.
- Self-referential calls —
stack.push(stack.top()),stack.push(std::move(stack.top())),stack.emplace(stack.top())— must work correctly even when the call happens to trigger a reallocation. Arguments that alias into the current buffer must not be read after that buffer is freed. - If the new capacity or the byte count
sizeof(T) * new_capacitywould overflowstd::size_t, throwstd::length_errorbefore touching the allocator. - Assume
Tis destructible and at least move- or copy-constructible.
Part 1 — Raw Storage and Object Lifetimes
Implement the class using separately allocated untyped storage, placement new for construction, explicit destructor calls, and a capacity-doubling growth strategy.
Your answer should address:
- The difference between "bytes that have been allocated" and "live
Tobjects that exist in those bytes." - How you ensure that constructors run for exactly the occupied slots and destructors run for exactly those same slots.
- How live elements are relocated when the buffer must grow, and what happens if a copy or move constructor throws partway through.
- The specific steps that make a self-referential
pushoremplacesafe when the buffer is full. - How you detect capacity or byte-count overflow before calling the allocator.
- How move construction and move assignment transfer ownership without double-freeing.
Part 2 — Four Ways to Allocate: Pick the Right One
Compare these four approaches: new T[n], malloc, ::operator new, and placement new paired with explicit destruction.
For each, state whether it allocates storage, whether it begins object lifetime, whether it invokes constructors, and what the correct paired cleanup is.
Your answer should explain:
- Why
mallocalone is not sufficient whenThas a nontrivial constructor. - How a
new-expression bundles allocation and construction into one step — and why that bundling is a problem here. - How
::operator newgives you raw, untyped storage without constructing anything. - Why placement new requires an explicit destructor call and does not own the storage it constructs into.
Part 3 — Why top Returns a Reference, and What Happens After pop
Justify the choice of T& and const T& as return types rather than T, T&&, or a single overload. Then analyze this snippet:
auto& a = stack.top();
stack.pop();
std::cout << a << '\n';
Your answer should cover:
- Why the mutable overload enables modification and the const overload enables read-only access on a const stack.
- What is lost — in type requirements and in copies — when returning by value instead.
- Why the ordinary
topaccessor should not advertise the stored value as an rvalue even though the object lives inside*this. - What has happened to the object
arefers to by the timestd::cout << aexecutes.
Part 4 — Where Arguments and Return Values Actually Live
Explain, at both the C++ abstract-machine level and the level of a real calling convention, where function arguments and return values can reside during a call. Cover registers, stack slots, caller-allocated return storage, references, and copy/move elision. Do not claim that any one location is universally required.
Your answer should distinguish:
- What the C++ standard guarantees versus what a specific ABI decides.
- How a concrete ABI (e.g., System V AMD64) handles small scalars versus larger aggregates.
- What "hidden pointer" or "return value slot" means for a function returning a large object by value.
- How returning a reference differs from returning an object by value in both language semantics and generated code.
Hints
Hint 1
Before any reallocation, copy or move the argument you were given into a local temporary — that way the argument survives even if the old buffer is freed underneath it.
Hint 2
::operator new(n * sizeof(T)) gives you a void* to n*sizeof(T) raw bytes with no objects in them yet; paired with explicit destructor calls and ::operator delete, it is the right primitive for a container that controls its own lifetimes.
Hint 3
After stack.pop() destroys the top element, the reference returned by the earlier top() call is dangling — reading through it is undefined behavior regardless of whether the memory has been reused.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is really four separate questions wrapped in one implementation. Nail the code first, then walk through each conceptual layer. A strong answer always writes the actual class before explaining the theory — hand-waving without code is not convincing.
Part 1 — Implementation
The core insight: ::operator new gives you a slab of bytes. Nothing lives there yet. new (ptr) T(args...) constructs a T at that address. ptr->~T() destroys it. ::operator delete(ptr) frees the slab. Keep size_ and capacity_ as separate counters; only indices [0, size_) hold live objects.
#include <cstddef>
#include <stdexcept>
#include <limits>
#include <utility>
#include <new>
template <class T>
class Stack {
public:
Stack() : data_(nullptr), size_(0), cap_(0) {}
~Stack() {
destroy_all();
::operator delete(data_);
}
Stack(Stack&& o) noexcept
: data_(o.data_), size_(o.size_), cap_(o.cap_) {
o.data_ = nullptr;
o.size_ = o.cap_ = 0;
}
Stack& operator=(Stack&& o) noexcept {
if (this != &o) {
destroy_all();
::operator delete(data_);
data_ = o.data_; size_ = o.size_; cap_ = o.cap_;
o.data_ = nullptr; o.size_ = o.cap_ = 0;
}
return *this;
}
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
// lvalue push — stage a copy first to survive self-referential calls
void push(const T& value) {
T staged(value); // copy before potential reallocation
grow_if_needed();
new (slot(size_)) T(std::move(staged));
++size_;
}
// rvalue push — move the argument out before reallocating
void push(T&& value) {
T staged(std::move(value)); // evacuate before reallocation
grow_if_needed();
new (slot(size_)) T(std::move(staged));
++size_;
}
template <class... Args>
T& emplace(Args&&... args) {
// Args may refer into the current buffer; construct into a temporary
// on the stack frame first, then move into live storage.
T staged(std::forward<Args>(args)...);
grow_if_needed();
T* p = new (slot(size_)) T(std::move(staged));
++size_;
return *p;
}
void pop() {
if (size_ == 0) throw std::out_of_range("pop on empty stack");
slot(size_ - 1)->~T();
--size_;
}
T& top() {
if (size_ == 0) throw std::out_of_range("top on empty stack");
return *slot(size_ - 1);
}
const T& top() const {
if (size_ == 0) throw std::out_of_range("top on empty stack");
return *slot(size_ - 1);
}
bool empty() const noexcept { return size_ == 0; }
std::size_t size() const noexcept { return size_; }
private:
void* data_;
std::size_t size_;
std::size_t cap_;
T* slot(std::size_t i) const {
return reinterpret_cast<T*>(data_) + i;
}
void destroy_all() {
for (std::size_t i = size_; i > 0; --i)
slot(i - 1)->~T();
}
void grow_if_needed() {
if (size_ < cap_) return;
constexpr std::size_t max_cap =
std::numeric_limits<std::size_t>::max() / sizeof(T);
std::size_t new_cap = cap_ == 0 ? 1 : cap_;
if (new_cap > max_cap / 2)
throw std::length_error("Stack capacity overflow");
new_cap *= 2;
// byte count overflow check already covered: new_cap <= max_cap
void* new_buf = ::operator new(new_cap * sizeof(T));
// relocate live objects; clean up on partial failure
std::size_t moved = 0;
try {
for (; moved < size_; ++moved)
new (reinterpret_cast<T*>(new_buf) + moved)
T(std::move_if_noexcept(*slot(moved)));
} catch (...) {
for (std::size_t k = moved; k > 0; --k)
(reinterpret_cast<T*>(new_buf) + k - 1)->~T();
::operator delete(new_buf);
throw;
}
destroy_all();
::operator delete(data_);
data_ = new_buf;
cap_ = new_cap;
}
};
Exception safety: push and emplace are strongly exception-safe. If staging or relocation throws, the stack is unchanged. Once new_buf is committed and the old buffer freed, only ++size_ remains, which cannot throw.
Self-referential safety: staging happens before grow_if_needed(), so the argument is safely in a local variable on the call stack when the old buffer is freed.
Part 2 — Four Allocation Mechanisms
| Mechanism | Allocates bytes | Begins lifetime | Calls constructor | Correct cleanup |
|---|---|---|---|---|
new T[n] | yes | yes | yes (default) | delete[] |
malloc(n) | yes | no | no | free |
::operator new(n) | yes | no | no | ::operator delete |
placement new (p) T(...) | no | yes | yes | p->~T(), then free separately |
malloc fails for a nontrivial T because nothing ever calls the constructor — you get an object-shaped hole filled with garbage. new T[n] calls the constructor, which is wrong here because we need to defer construction until an element is actually pushed. ::operator new is the right primitive: raw bytes, no objects, pairs with ::operator delete. Placement new then constructs exactly when and where we choose.
Part 3 — Reference Return Type and Dangling After pop
Returning T& lets the caller mutate the top element in place (stack.top() = x) without an extra copy. The const T& overload makes the same element accessible on a const Stack<T> without stripping const. Returning by value would require T to be copyable, would silently copy on every top() call, and would break mutation.
Returning T&& would be actively harmful — it invites the caller to move out of a slot that still exists inside the stack, leaving a moved-from object that pop will later destroy. The element is an lvalue stored inside *this; it should be exposed as an lvalue.
The snippet:
auto& a = stack.top(); // a binds to the live top element
stack.pop(); // destructor runs; object lifetime ends
std::cout << a << '\n'; // undefined behavior — dangling reference
After pop, the T that a refers to has been destroyed. The memory may still be mapped, which is why this can appear to work in testing, but the standard provides no guarantee. It is undefined behavior.
Part 4 — Where Arguments and Return Values Live
The C++ standard defines an abstract machine: arguments are passed and values are returned, but the standard says nothing about registers or stack frames. That is entirely ABI territory.
Under a concrete ABI like System V AMD64: integer and pointer arguments fill rdi, rsi, rdx, rcx, r8, r9 before spilling to the stack. Floating-point arguments use XMM registers. Small return values (fitting in one or two registers) come back in rax/rdx. When a function returns a large aggregate that does not fit in registers, the caller allocates space (typically on its own stack frame) and passes a hidden pointer as an extra first argument; the callee writes the result there directly.
Returning a reference is fundamentally different: the function returns a pointer-sized value (the address), not the object itself. No hidden pointer, no copy, no elision needed. This is why top() returning T& is cheaper than returning T for any nontrivial type.
Copy/move elision (NRVO, guaranteed copy elision since C++17 for prvalues) means the compiler may construct the return value directly in the caller's storage, eliminating a copy entirely. This is a compiler optimization (mandatory for prvalues in C++17, permitted otherwise), not a language guarantee about where the object "is."
Common mistakes to avoid:
- Claiming "arguments are always passed on the stack" — wrong for any modern ABI with register passing.
- Treating
::operator newandnew Tas interchangeable — they are not; one constructs, the other does not. - Forgetting to stage self-referential arguments before reallocation — this is the subtlest correctness bug in the implementation.
- Returning
T&&fromtop— this silently enables moving from a live stack slot. - Using
size_as a loop bound after partial construction fails during growth — you must track exactly how many objects were successfully constructed in the new buffer before the throw.