Build a Reference-Counted Smart Pointer in C++
System DesignModel answerLast 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
- Class interface — what constructors, operators, and observers the type exposes, and how an empty (null) state is represented.
- Ownership model — how multiple pointer instances track a single live object without copying it.
- Copy and move behavior — what happens to ownership counts on copy-construction, move-construction, copy-assignment, and move-assignment, including self-assignment.
- Object lifetime — exactly when and how the managed object is destroyed, and what invariant ties the owner count to that decision.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Scoping the problem
Before writing any code, state the boundaries: single-threaded, one type parameter, no weak references, no custom deleter, no array support. That removes the hardest parts of std::shared_ptr and isolates the ownership logic worth discussing.
The control block
The central insight is that shared ownership requires a single piece of heap memory that every co-owner can reach. A raw pointer to the object is not enough — you also need a reference count that outlives any individual owner. That heap-allocated record is the control block:
struct ControlBlock {
long use_count;
// In a full implementation: weak_count, deleter, allocator
};
When the first SharedPtr<T> is constructed from a raw pointer, it allocates one ControlBlock with use_count = 1. Every subsequent copy increments use_count; every destructor decrements it. When the count hits zero, the managed object is destroyed and the control block is freed.
Invariant: at all times, use_count equals the number of SharedPtr instances that point to this control block.
Full implementation
#include <cassert>
#include <utility>
struct ControlBlock {
long use_count = 0;
};
template <typename T>
class SharedPtr {
public:
// Construct from raw pointer; takes ownership.
// Never pass the same raw pointer to two separate SharedPtr constructors.
explicit SharedPtr(T* ptr = nullptr)
: ptr_(ptr), ctrl_(ptr ? new ControlBlock{1} : nullptr) {}
// Copy: both instances now co-own the object.
SharedPtr(const SharedPtr& other) noexcept
: ptr_(other.ptr_), ctrl_(other.ctrl_) {
if (ctrl_) ++ctrl_->use_count;
}
// Move: transfer ownership; leave source empty.
SharedPtr(SharedPtr&& other) noexcept
: ptr_(other.ptr_), ctrl_(other.ctrl_) {
other.ptr_ = nullptr;
other.ctrl_ = nullptr;
}
// Copy-assignment: increment first, then decrement — safe for self-assignment.
SharedPtr& operator=(const SharedPtr& other) noexcept {
if (ctrl_ != other.ctrl_) { // skip only when truly the same block
if (other.ctrl_) ++other.ctrl_->use_count;
release();
ptr_ = other.ptr_;
ctrl_ = other.ctrl_;
}
return *this;
}
// Move-assignment: release current ownership, steal from source.
SharedPtr& operator=(SharedPtr&& other) noexcept {
if (this != &other) {
release();
ptr_ = other.ptr_;
ctrl_ = other.ctrl_;
other.ptr_ = nullptr;
other.ctrl_ = nullptr;
}
return *this;
}
~SharedPtr() { release(); }
// Observers
T* get() const noexcept { return ptr_; }
T& operator*() const noexcept { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
long use_count() const noexcept { return ctrl_ ? ctrl_->use_count : 0; }
explicit operator bool() const noexcept { return ptr_ != nullptr; }
// Drop this instance's ownership; optionally replace with a new object.
void reset(T* ptr = nullptr) {
release();
ptr_ = ptr;
ctrl_ = ptr ? new ControlBlock{1} : nullptr;
}
private:
T* ptr_ = nullptr;
ControlBlock* ctrl_ = nullptr;
void release() noexcept {
if (!ctrl_) return;
if (--ctrl_->use_count == 0) {
delete ptr_;
delete ctrl_;
}
ptr_ = nullptr;
ctrl_ = nullptr;
}
};
Copy-assignment order matters
Incrementing before decrementing is the canonical fix for self-assignment. If you decrement first and the count was already 1, you destroy the object before the increment can protect it. Using a ctrl_ != other.ctrl_ guard is equally correct and avoids the spurious inc/dec on the common self-assignment path.
Test sketch
int main() {
SharedPtr<int> a(new int(42));
assert(a.use_count() == 1);
SharedPtr<int> b = a; // copy
assert(a.use_count() == 2);
assert(b.use_count() == 2);
SharedPtr<int> c = std::move(b); // move; b is now empty
assert(!b);
assert(c.use_count() == 2);
SharedPtr<int> d(new int(99));
a = d; // assign across groups; old group count drops to 1
assert(a.use_count() == 2);
assert(c.use_count() == 1); // c is now the sole owner of 42
// c goes out of scope here -> use_count hits 0 -> 42 is deleted
}
Known extensions and what they require
- Weak references — a second count (
weak_count) in the control block; keep the block alive until both counts reach zero, but allow the object to be destroyed when onlyuse_counthits zero. - Thread safety — replace
long use_countwithstd::atomic<long>and usefetch_subwith a release/acquire fence to safely destroy only once. - Custom deleters — store a
std::function<void(T*)>in the control block; type-erased deleters also enablevoid*object storage, which is howstd::shared_ptr's aliasing constructor works. - Array ownership — specialize on
T[], replacedelete ptr_withdelete[] ptr_, and disableoperator*/operator->.
Common mistakes
- Two independent groups for one raw pointer.
SharedPtr<T> a(p); SharedPtr<T> b(p);creates two control blocks; whichever destructs last is a double-free.std::make_sharedexists partly to make this impossible by construction. - Ref-count safety ≠ data-race safety. An atomic control block ensures the object is destroyed exactly once; it says nothing about whether the object's own methods are safe to call concurrently from two threads.
- Cycles. Two objects holding
SharedPtrto each other produce a count that never reaches zero. This is not a bug in the implementation — it is a fundamental limit of reference counting. Weak pointers break cycles by observing without owning.