KatInterview

Build a Type-Safe C++ Stack from Raw Storage

Stacks & QueuesModel answer
HardModel answerStacks & QueuesC++memory-managementtemplates

Last 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 top or pop on an empty stack must throw std::out_of_range.
  • push, emplace, top, pop, empty, and size are 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_capacity would overflow std::size_t, throw std::length_error before touching the allocator.
  • Assume T is 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 T objects 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 push or emplace safe 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 malloc alone is not sufficient when T has a nontrivial constructor.
  • How a new-expression bundles allocation and construction into one step — and why that bundling is a problem here.
  • How ::operator new gives 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 top accessor should not advertise the stored value as an rvalue even though the object lives inside *this.
  • What has happened to the object a refers to by the time std::cout << a executes.

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.