Build a Reference-Counted Shared Ownership Pointer in C++
Data Structure DesignModel answerLast updated
Implement a thread-safe shared ownership smart pointer class template from scratch, covering copy/move semantics, atomic reference counting, and correct destruction.
Shared Ownership Smart Pointer
Modern C++ programs often need several parts of a system to jointly own a heap-allocated object — none of them individually responsible for freeing it, yet the object must be freed exactly once when the last owner is done. Your task is to build that mechanism yourself.
Implement a class template SharedPtr<T> that provides shared ownership semantics for a single heap-allocated object. The object must stay alive as long as at least one SharedPtr refers to it, and must be destroyed the moment the last one is released — no sooner, no later.
Required interface
template <typename T>
class SharedPtr {
public:
SharedPtr() noexcept; // empty; owns nothing
explicit SharedPtr(T* p); // takes ownership of p (new-allocated)
SharedPtr(const SharedPtr& other); // shares ownership
SharedPtr(SharedPtr&& other) noexcept; // transfers ownership; other becomes empty
SharedPtr& operator=(const SharedPtr& other);
SharedPtr& operator=(SharedPtr&& other) noexcept;
~SharedPtr();
void reset(T* p = nullptr); // drop current object; optionally own p
T* get() const noexcept;
T& operator*() const;
T* operator->() const noexcept;
explicit operator bool() const noexcept;
std::size_t use_count() const noexcept; // 0 when empty
};
Constraints
- C++17 or later. You may not use
std::shared_ptr,std::unique_ptr, orstd::weak_ptr. - The pointer manages single objects allocated with
new, not arrays. - An empty
SharedPtr— including one constructed fromnullptr— must reportuse_count() == 0. - Reference count updates must be safe when copies of the same
SharedPtrare created or destroyed concurrently on different threads.
What you should be ready to discuss
- Where the reference count is stored and who is responsible for freeing it.
- The exact memory ordering used for atomic count operations and why you chose it.
- Which operations are thread-safe and which are not.
- What happens on self-assignment and why it matters.
- How the implementation would change to support a non-owning (
weak) reference, base-class conversion, or a custom deleter.
Hints
Hint 1
You need a single reference count that all copies of the same SharedPtr can see and modify. Think about where to allocate it and who frees it — it has a different lifetime than the managed object itself.
Hint 2
Atomic increment and decrement avoid data races on the count, but memory ordering matters: what must be visible to the thread that observes the count drop to zero before it calls delete?
Hint 3
Write copy assignment as: increment the incoming count first, then release the old object. That one ordering makes both self-assignment and exception safety fall out naturally without a special-case check.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Control block
Every SharedPtr that shares an object needs access to a single count. The standard solution is a small heap-allocated control block that holds the count alongside (optionally) the object itself. A bare SharedPtr stores two raw pointers: one to the managed T, one to the control block. When the count drops to zero the managed object is deleted; the control block itself is deleted at the same time (in the basic version without weak pointers).
┌────────────┐ ptr_ ┌───┐
│ SharedPtr │ ──────────► │ T │
│ │ ctrl_ ├───┤
│ │ ──────────► │ N │ ← atomic count
└────────────┘ └───┘
Memory ordering
The count must be std::atomic<std::size_t>. The right orderings are:
- Increment (
fetch_add) —relaxedis enough. The only guarantee needed is that the new value is visible eventually; no memory operations need to be sequenced around it. - Decrement (
fetch_sub) — needsacq_rel. Thereleasehalf ensures that all writes done by this thread before the decrement are visible to whoever observes the final zero. Theacquirehalf on the thread that sees zero ensures it sees those writes before it callsdelete.
What is not thread-safe: concurrent access to the same SharedPtr object (e.g., assigning to one instance while another thread reads from it). Thread safety covers the count, not the pointer itself.
Complete implementation
#include <atomic>
#include <cstddef>
#include <utility>
struct ControlBlock {
std::atomic<std::size_t> count;
explicit ControlBlock(std::size_t n) : count(n) {}
};
template <typename T>
class SharedPtr {
public:
// Empty
SharedPtr() noexcept : ptr_(nullptr), ctrl_(nullptr) {}
// Take ownership of a raw pointer.
// Strong exception guarantee: if 'new ControlBlock' throws, p is deleted.
explicit SharedPtr(T* p) : ptr_(p), ctrl_(nullptr) {
if (p) {
try {
ctrl_ = new ControlBlock(1);
} catch (...) {
delete p;
throw;
}
}
}
// Copy: share ownership
SharedPtr(const SharedPtr& other) noexcept
: ptr_(other.ptr_), ctrl_(other.ctrl_) {
inc();
}
// Move: transfer ownership, leave other empty
SharedPtr(SharedPtr&& other) noexcept
: ptr_(other.ptr_), ctrl_(other.ctrl_) {
other.ptr_ = nullptr;
other.ctrl_ = nullptr;
}
// Copy assignment: increment first, then release old — handles self-assignment
SharedPtr& operator=(const SharedPtr& other) noexcept {
// Bump incoming count before releasing ours
if (other.ctrl_) {
other.ctrl_->count.fetch_add(1, std::memory_order_relaxed);
}
release();
ptr_ = other.ptr_;
ctrl_ = other.ctrl_;
return *this;
}
// Move assignment
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(); }
void reset(T* p = nullptr) {
SharedPtr tmp(p); // may throw; current state unchanged until swap
swap(tmp);
}
T* get() const noexcept { return ptr_; }
T& operator*() const { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
explicit operator bool() const noexcept { return ptr_ != nullptr; }
std::size_t use_count() const noexcept {
return ctrl_ ? ctrl_->count.load(std::memory_order_relaxed) : 0;
}
private:
T* ptr_;
ControlBlock* ctrl_;
void inc() noexcept {
if (ctrl_) ctrl_->count.fetch_add(1, std::memory_order_relaxed);
}
void release() noexcept {
if (!ctrl_) return;
if (ctrl_->count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete ptr_;
delete ctrl_;
}
ptr_ = nullptr;
ctrl_ = nullptr;
}
void swap(SharedPtr& other) noexcept {
std::swap(ptr_, other.ptr_);
std::swap(ctrl_, other.ctrl_);
}
};
Complexity
- Every operation is O(1).
- Two heap allocations per managed object (one for
T, one forControlBlock). A make-style factory that allocates them in a single block — the make_shared optimization — halves allocations at the cost of a slightly longer control block lifetime.
Common mistakes
| Mistake | Consequence |
|---|---|
Using seq_cst everywhere | Correct but unnecessarily expensive on x86 and especially on ARM |
relaxed on decrement | The thread that sees zero may not see prior writes; undefined behavior when it calls delete |
Checking this != &other in copy assignment | Masks the real fix; fragile — doesn't help when two SharedPtrs share the same object but are different instances |
Forgetting to null ptr_/ctrl_ after release | Destructor runs again on the same block — double free |
Leaking p when new ControlBlock throws | Violates the constructor's ownership contract |
Extensions worth discussing
- Weak pointer: add a second atomic count (
weak_count) to the control block; the control block is freed only when both counts reach zero. - Base-class conversion: add a converting constructor
template <typename U> SharedPtr(const SharedPtr<U>& other)gated onstd::is_convertible_v<U*, T*>. - Custom deleter: store a
std::function<void(T*)>in the control block and call it instead ofdelete ptr_.