KatInterview

Build a Reference-Counted Smart Pointer in C++

System DesignModel answer
MediumModel answerSystem Designc++memory-managementsmart-pointers

Last updated

Design a shared-ownership pointer class: explain the control block, copy/move semantics, destruction invariants, and the boundaries of reference counting.

Build a Reference-Counted Smart Pointer in C++

You are asked to design a small shared-ownership pointer library from scratch in C++. Rather than using std::shared_ptr, walk through how you would build the equivalent yourself.

What to cover

  1. Class interface — what constructors, operators, and observers the type exposes, and how an empty (null) state is represented.
  2. Ownership model — how multiple pointer instances track a single live object without copying it.
  3. Copy and move behavior — what happens to ownership counts on copy-construction, move-construction, copy-assignment, and move-assignment, including self-assignment.
  4. Object lifetime — exactly when and how the managed object is destroyed, and what invariant ties the owner count to that decision.
  5. Edge cases and failure modes — allocation failure, reset, and why constructing two independent ownership groups from the same raw pointer is a bug.

Scope

Treat this as a single-threaded library managing one object of a matching type. You do not need to implement weak references, array ownership, custom deleters, aliasing constructors, or thread-safe reference counting — but you should name each of these as a known extension and briefly describe what would be needed to support it.

What is expected

A clear prose explanation of the design, supported by a working C++ implementation. Include a short test sketch that exercises: constructing an owner, copying it, moving it, assigning between two independent ownership groups, and verifying the count reaches zero at destruction.

Hints

Hint 1

The control block is the core of the design. Ask yourself: what data lives there, who allocates it, and who is responsible for freeing it?

Hint 2

Walk through copy-assignment step by step. You need to increment the new referent's count before decrementing the old one — in that order — to survive self-assignment correctly.

Hint 3

Reference counting solves lifetime, not cycles. Be ready to explain why two objects that each hold a shared pointer to the other will never be destroyed, and what mechanism addresses that.