Build a Reference-Counted Pointer from Scratch in C++
Data Structure DesignModel answerLast updated
Implement a class template SharedPtr<T> that manages heap object lifetime through reference counting, supporting copy, move, reset, and safe self-assignment.
Build a Reference-Counted Pointer from Scratch in C++
The C++ standard library's std::shared_ptr is one of the most important tools for safe heap memory management. Your task is to build a simplified version of it from first principles.
What to implement
Write a class template SharedPtr<T> that takes ownership of a heap-allocated T* and ensures the object is destroyed exactly once — when the last SharedPtr that owns it goes out of scope or releases it.
Your implementation must support:
- Default constructor — creates a null, non-owning pointer
- Constructor from
T*— takes ownership of the given raw pointer - Destructor — releases ownership; deletes the object if this was the last owner
- Copy constructor and copy assignment — both objects end up sharing ownership; the reference count increases by one
- Move constructor and move assignment — ownership transfers to the new object; the source becomes null
T& operator*()andT* operator->()— dereference the managed objectT* get() const— returns the raw pointer without transferring ownershipsize_t use_count() const— returns how manySharedPtrinstances currently own the objectvoid reset(T* p = nullptr)— releases the current object and optionally takes ownership of a new one
Rules and constraints
- The managed object must be deleted exactly once. No double-frees, no leaks.
- Self-assignment (
a = a) and self-move (a = std::move(a)) must both be handled correctly. use_count()on a nullSharedPtrmust return0.- You do not need to support thread-safety unless you want to — but note the trade-off.
- Constructing two independent
SharedPtrs from the same raw pointer is considered misuse; you do not need to detect it.
What a complete answer looks like
Provide:
- The full implementation of
SharedPtr<T>, with brief comments explaining non-obvious decisions - A walkthrough of why the implementation is correct — specifically, what invariant it maintains and how each operation preserves it
- Complexity analysis for each operation
- A discussion of the key edge cases and how your code handles them
Hints
Hint 1
The reference count must live on the heap and be shared by all copies — if it lived inside the SharedPtr object itself, copies could not see each other's changes. Allocate it alongside or separately from the managed object.
Hint 2
Copy-and-swap is the cleanest way to implement both copy and move assignment. Construct a temporary from the source (which updates the count correctly), swap it with *this, then let the temporary's destructor handle releasing the old state. Self-assignment becomes a non-issue because the count reaches 2 before anything is deleted.
Hint 3
In the constructor that takes a raw T*, if allocating the control block throws, you must delete the raw pointer before rethrowing — otherwise the object the caller handed you leaks with no way to recover it.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every SharedPtr that owns a given object needs to agree on a single reference count. That count cannot live inside any one SharedPtr instance, because copies are independent objects on the stack or heap. The standard solution is a control block: a small heap allocation that holds the count and is shared by all co-owners. Each SharedPtr carries two pointers — one to the managed object, one to the control block.
Here the control block is just a size_t. A production implementation would also store a custom deleter and a weak count, but the ownership mechanics are identical.
The core invariant
Either both
ptr_andcount_arenullptr, or*count_equals the exact number of liveSharedPtrobjects whosecount_points to that block.
Every operation must preserve this. The table below shows how:
| Operation | Effect on count |
|---|---|
SharedPtr(T* p) | allocate new block, set to 1 |
| copy constructor | ++*count_ |
| move constructor | no change; source becomes null |
destructor / release() | --*count_; delete object + block if 0 |
| copy/move assignment | copy-and-swap, so correctness is inherited |
Object deletion happens only when the count transitions from 1 to 0, which occurs at most once per control block. That eliminates both double-free and leaks.
Self-assignment safety via copy-and-swap
Copy assignment builds a temporary SharedPtr from other, which increments the count. It then swaps the temporary with *this and lets the temporary destroy the old state. If other is *this, the count momentarily reaches 2, the swap exchanges identical data, and the temporary destructor brings it back to 1. Nothing is deleted. The same pattern handles move assignment.
Exception safety in the raw-pointer constructor
When SharedPtr(T* p) is called and the new size_t(1) allocation throws, the managed object p would leak unless we catch it. The constructor must delete p before rethrowing. This is the one place where we hold a resource we cannot yet track.
Complexity
Every operation — construction, copy, move, assignment, reset, use_count, and dereference — is O(1) time. Each managed object incurs exactly one extra heap allocation (the control block) regardless of how many owners it has. Each SharedPtr instance is two pointers wide.
Edge cases
- Null construction: no control block is allocated.
use_count()returns 0, matchingstd::shared_ptr. reset(p)wherep == get(): naively this would release the current owner, decrement the count to 0, delete the object, then try to take ownership of the now-deleted pointer. Guard against it explicitly.- Two
SharedPtrs from the same raw pointer: creates two independent control blocks and a guaranteed double-free. There is no way to detect this through a raw-pointer interface. The correct remedy ismake_shared, which allocates the object and the control block together so no raw pointer ever escapes. - Moved-from state: must be null and safe to destroy, assign to, or reset.
const-correctness: accessor operators areconston theSharedPtrbecause the pointer's constness is shallow — aconst SharedPtr<T>still grants mutable access toT, just like aT* const.
Common mistakes
- Putting the counter inside the
SharedPtrstruct — copies can't share it. - Forgetting to null out the source in the move constructor — leads to double-free when both objects are destroyed.
- Handling self-assignment with
if (this == &other)instead of copy-and-swap — misses self-move and is generally fragile. - Not cleaning up
pwhen the control block allocation throws.
Implementation
#include <cassert>
#include <cstddef>
#include <utility>
#include <iostream>
template <typename T>
class SharedPtr {
public:
// Null, non-owning pointer. No control block allocated.
SharedPtr() noexcept : ptr_(nullptr), count_(nullptr) {}
// Take ownership of a raw heap pointer.
// Marked explicit to prevent silent implicit ownership transfers.
explicit SharedPtr(T* p) : ptr_(p), count_(nullptr) {
if (p) {
try {
count_ = new std::size_t(1);
} catch (...) {
delete p; // p would otherwise leak with no way to recover it
throw;
}
}
}
~SharedPtr() { release(); }
// Copy: both objects share ownership, count goes up by one.
SharedPtr(const SharedPtr& other) noexcept
: ptr_(other.ptr_), count_(other.count_) {
if (count_) ++*count_;
}
// Move: steal the state, leave the source null. Count is unchanged.
SharedPtr(SharedPtr&& other) noexcept
: ptr_(other.ptr_), count_(other.count_) {
other.ptr_ = nullptr;
other.count_ = nullptr;
}
// Copy assignment via copy-and-swap. Self-assignment safe:
// the temporary bumps the count before the old state is released.
SharedPtr& operator=(const SharedPtr& other) {
SharedPtr tmp(other);
swap(tmp);
return *this;
}
// Move assignment — same pattern.
SharedPtr& operator=(SharedPtr&& other) noexcept {
SharedPtr tmp(std::move(other));
swap(tmp);
return *this;
}
T& operator*() const noexcept {
assert(ptr_ && "dereferencing a null SharedPtr");
return *ptr_;
}
T* operator->() const noexcept { return ptr_; }
T* get() const noexcept { return ptr_; }
std::size_t use_count() const noexcept {
return count_ ? *count_ : 0;
}
explicit operator bool() const noexcept { return ptr_ != nullptr; }
// Release current ownership, optionally take ownership of p.
void reset(T* p = nullptr) {
// Guard: reset(get()) would free the object then alias the dead pointer.
if (p && p == ptr_) return;
SharedPtr(p).swap(*this); // temporary releases our old state on exit
}
void swap(SharedPtr& other) noexcept {
std::swap(ptr_, other.ptr_);
std::swap(count_, other.count_);
}
private:
// Decrement the count; delete the object and control block at zero.
void release() noexcept {
if (count_ && --*count_ == 0) {
delete ptr_;
delete count_;
}
ptr_ = nullptr;
count_ = nullptr;
}
T* ptr_;
std::size_t* count_;
};
// ---------------------------------------------------------------------------
// Smoke test
// ---------------------------------------------------------------------------
struct Widget {
static int alive;
int value;
explicit Widget(int v) : value(v) { ++alive; }
~Widget() { --alive; }
};
int Widget::alive = 0;
int main() {
{
SharedPtr<Widget> a(new Widget(1));
assert(a.use_count() == 1 && a->value == 1);
SharedPtr<Widget> b = a; // copy
assert(a.use_count() == 2 && b.use_count() == 2);
a = a; // self-assignment
assert(a.use_count() == 2);
SharedPtr<Widget> c = std::move(b); // move
assert(!b && c.use_count() == 2);
c.reset(new Widget(2)); // c leaves the group
assert(a.use_count() == 1 && Widget::alive == 2);
a.reset(); // last owner of Widget(1)
assert(Widget::alive == 1);
SharedPtr<Widget> empty;
assert(empty.use_count() == 0 && !empty);
}
assert(Widget::alive == 0); // no leaks, no double-free
std::cout << "All assertions passed.\n";
}
What interviewers probe next
- Weak references — how would you add
WeakPtr<T>to break cycles? (A second weak count in the control block; the block lives until both counts reach 0.) make_shared— why is it better? (Single allocation for object + control block; no risk of aliasing a raw pointer.)- Thread safety — what would it take? (
std::atomic<size_t>for the counter; does not make the pointed-to object thread-safe.) - Custom deleters — where do they live? (In the control block, as a type-erased callable.)