Build a Reference-Counted Smart Pointer in C++
Data Structure DesignModel answerLast updated
Design and implement a shared ownership pointer with automatic memory management using reference counting and RAII principles.
Problem
Memory safety is essential in systems code. Write a generic smart pointer template RefPtr<T> that provides shared ownership semantics: the managed resource is automatically freed when the final owner is destroyed.
Multiple RefPtr instances can point to the same object. The object persists as long as at least one RefPtr owns it, and is deleted exactly once when the last owner goes away.
Interface
Your RefPtr must support:
template<typename T>
class RefPtr {
public:
// Takes ownership of a raw pointer (may be nullptr)
explicit RefPtr(T* ptr = nullptr);
// Cleanup
~RefPtr();
// Copying increases reference count
RefPtr(const RefPtr& other);
RefPtr& operator=(const RefPtr& other);
// Moving transfers ownership without changing count
RefPtr(RefPtr&& other) noexcept;
RefPtr& operator=(RefPtr&& other) noexcept;
// Access the managed object
T& operator*() const;
T* operator->() const;
T* get() const;
// Query how many owners currently exist
size_t use_count() const;
// Release current resource and optionally take a new one
void reset(T* ptr = nullptr);
};
Example Behavior
RefPtr<int> p1(new int(10));
assert(p1.use_count() == 1);
assert(*p1 == 10);
{
RefPtr<int> p2 = p1; // p2 shares ownership
assert(p1.use_count() == 2);
assert(p2.use_count() == 2);
*p2 = 50;
}
// p2 destroyed here
assert(p1.use_count() == 1);
assert(*p1 == 50); // modification visible through p1
p1.reset(); // releases the int
assert(p1.get() == nullptr);
assert(p1.use_count() == 0);
Constraints
- Handle self-assignment correctly (
p = p;must not corrupt state) - Support nullptr initialization without unnecessary allocations
- Ensure the managed object is deleted exactly once
- Moving should not increment or decrement the reference count
reset()must safely transition between different owned objects
Explain your design, implementation strategy, time and space complexity, and how you handle the key edge cases.
Hints
Hint 1
The reference count must be shared across all copies—it cannot live inside each instance
Hint 2
Use two raw pointers: one to the managed object, one to a heap-allocated counter
Hint 3
Build copy and move assignment using temporary objects and swap to handle self-assignment automatically
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is that every copy of a RefPtr must share the same counter. If the counter were a member variable, each copy would have its own separate count, which defeats the purpose. The solution: allocate the counter on the heap and store a pointer to it.
Each RefPtr instance holds two raw pointers:
obj_: points to the managed object of typeTrefcount_: points to a heap-allocatedsize_tthat counts how manyRefPtrinstances currently share ownership
When refcount_ is non-null, *refcount_ always equals the number of live RefPtr instances pointing to it. Operations maintain this invariant:
Constructor with non-null pointer: Allocate a counter initialized to 1, since this is the first owner. If the allocation fails, delete the object we were given to avoid leaking it.
Constructor with nullptr: Set both pointers to null. No counter allocation needed. use_count() returns 0 for null pointers.
Copy constructor: Two instances now share ownership, so increment the counter.
Destructor: One fewer owner, so decrement. If the counter reaches zero, no owners remain—delete both the object and the counter.
Move constructor: Transfer ownership from source to destination. The total number of owners stays the same, so don't touch the counter. Null out the source so its destructor becomes a no-op.
Copy assignment: Use the copy-and-swap idiom. Create a temporary copy (which increments the count), swap it with *this, then let the temporary destruct (which releases our old state). This handles self-assignment automatically: the increment happens before the decrement, so the counter never hits zero mid-operation.
Move assignment: Similar pattern with a moved-from temporary.
reset(p): Equivalent to constructing a new RefPtr(p) and swapping it with *this. The new resource is acquired before the old one is released, providing strong exception safety.
This design ensures the managed object is destroyed exactly once: only the final owner sees the counter drop to zero, and that owner then deletes both the object and the counter.
Complexity
- Time: All operations are O(1), excluding the cost of running
T's destructor when the last reference is released. - Space: Each
RefPtrstores two pointers (typically 16 bytes on 64-bit systems). Each managed object requires one additional heap allocation for thesize_tcounter.
Edge Cases
Self-assignment (p = p;): The copy-and-swap pattern handles this safely. The temporary copy increments the count before the swap, so the count never drops to zero during the operation.
Null pointers: A RefPtr constructed with nullptr allocates no counter. use_count() checks whether refcount_ is null and returns 0 if so. Copying a null pointer produces another null pointer with no counter.
Self-move (p = std::move(p);): The move-and-swap pattern leaves the object in a valid moved-from state. It's safe but inefficient.
reset() with the same pointer (p.reset(p.get())): This causes undefined behavior—a double delete. The new RefPtr takes ownership and deletes the object when it destructs, then the old one tries to delete it again. This matches standard library behavior and is worth mentioning as a caller mistake.
Dereferencing null: Undefined behavior. An assertion helps catch this in debug builds.
Thread safety: This implementation is not thread-safe. Multiple threads modifying the same RefPtr instance or accessing the pointee concurrently need external synchronization. Making the counter atomic would allow concurrent copying and destruction of different instances that share the same object.
Implementation
#include <cstddef>
#include <utility>
#include <cassert>
template<typename T>
class RefPtr {
public:
explicit RefPtr(T* ptr = nullptr) : obj_(ptr), refcount_(nullptr) {
if (obj_) {
try {
refcount_ = new std::size_t(1);
} catch (...) {
delete obj_; // avoid leaking the object if allocation fails
throw;
}
}
}
~RefPtr() {
release();
}
RefPtr(const RefPtr& other) : obj_(other.obj_), refcount_(other.refcount_) {
if (refcount_) {
++(*refcount_);
}
}
RefPtr& operator=(const RefPtr& other) {
RefPtr temp(other); // acquire new resource first
swap(temp); // swap with temporary
return *this; // temp destructs, releasing old resource
}
RefPtr(RefPtr&& other) noexcept
: obj_(other.obj_), refcount_(other.refcount_) {
other.obj_ = nullptr;
other.refcount_ = nullptr;
}
RefPtr& operator=(RefPtr&& other) noexcept {
RefPtr temp(std::move(other));
swap(temp);
return *this;
}
T& operator*() const {
assert(obj_ != nullptr && "dereferencing null RefPtr");
return *obj_;
}
T* operator->() const {
return obj_;
}
T* get() const {
return obj_;
}
std::size_t use_count() const {
return refcount_ ? *refcount_ : 0;
}
void reset(T* ptr = nullptr) {
RefPtr temp(ptr);
swap(temp);
}
void swap(RefPtr& other) noexcept {
std::swap(obj_, other.obj_);
std::swap(refcount_, other.refcount_);
}
private:
void release() noexcept {
if (refcount_) {
--(*refcount_);
if (*refcount_ == 0) {
delete obj_;
delete refcount_;
}
}
obj_ = nullptr;
refcount_ = nullptr;
}
T* obj_;
std::size_t* refcount_;
};
Common Mistakes
Storing the count by value: If each RefPtr has its own counter member, copies don't share state. The first copy to destruct deletes the object, leaving dangling pointers in the others.
Forgetting exception safety in the constructor: If new size_t(1) throws after we've stored ptr, the constructor exits without cleaning up, leaking the object.
Decrementing before incrementing in assignment: *this = other must increment other's count before decrementing our own. Otherwise *this = *this decrements to zero and deletes the object prematurely.
Using delete[] for arrays: Plain delete is incorrect for new T[]. Supporting arrays requires a custom deleter, which is beyond this scope.
Manual branches for self-assignment: The copy-and-swap idiom handles it automatically and correctly. Special-case checks add complexity without benefit.