English

Writing a shared_ptr by Hand

6/28/2026
25
 Writing a shared_ptr by Hand


std::shared_ptr feels like magic the first time you use it: objects clean themselves up exactly when the last owner goes away, and you never call `delete`. But there's no magic — just a reference count, a few special member functions, and one genuinely clever trick for thread safety.

The best way to understand it is to build one.

In this article we'll grow a smart pointer from a naive first attempt into a thread-safe shared_ptr with a working weak_ptr, fixing real bugs along the way.

By the end you'll understand:
* The control block and why it exists
* RAII and the Rule of Five
* Perfect forwarding in a make_shared factory
* Why ref counts must be atomic
* How weak_ptr solves the dangling-pointer problem, and the lock-free CAS loop that makes lock() safe

1. The core idea: a shared control block

A shared_ptr is "shared" because multiple pointer objects can own the same heap object. Someone has to count how many owners there are so the object is destroyed when — and only when — the last one goes away.That counter can't live inside the pointer objects (they're separate copies). It lives in a separate heap allocation called the control block, which every owner points to:

Our control block starts simple:

C++
template <typename T>
struct ControlBlock
{
    T   *ptr;       // the managed object
    long ref_cnt;   // how many SimpleSharedPtr own it

    explicit ControlBlock(T *p) : ptr(p), ref_cnt(1) {}
};

When a new owner appears, bump ref_cnt. When one goes away, drop it. At zero, delete the object. That's the whole game.  

2. A first attempt — and why it's broken

Here's the version almost everyone writes first:

C++
template <typename T>
class SimpleSharedPtr
{
    ControlBlock<T> *cb_;
    
    void release()
    {
        if (!cb_)
            return;

        if (--cb_->ref_cnt == 0)   // last owner?
        {
            delete cb_->ptr;       // destroy the object
            delete cb_;            // and the control block
        }
        cb_ = nullptr;
    }

public:
    explicit SimpleSharedPtr(T *p = nullptr)
    {
        cb_ = p ? new ControlBlock<T>(p) : nullptr;
    }
    
    ~SimpleSharedPtr() { release(); }

    long use_count() const { return cb_ ? cb_->ref_cnt : 0; }
    T*   get()       const { return cb_ ? cb_->ptr     : nullptr; }
};

RAII — Resource Acquisition Is Initialization — is the principle behind every C++ smart pointer: a resource's lifetime is bound to an object's lifetime. Acquire in the constructor, release in the destructor. When the object goes out of scope, cleanup happens automatically.


It used RAII in the destructor to release the saved object once the ref_cnt is decreased to 0 and it compiles. but it's badly broken - Copying it is a disaster. There is no copy constructor, so the compiler generates one that does a shallow copy of cb_

C++
auto a = SimpleSharedPtr<Node>(new Node(1));
auto b = a;   // both a.cb_ and b.cb_ point to the SAME control block
              // ref_cnt is still 1 — the count is now a lie

3. The Rule of Five

If a class manages a resource and needs a custom destructor, it almost certainly also needs a custom copy constructor, copy assignment, move constructor, and move assignment. That's the Rule of Five.

Our class manages a raw owning pointer, so we need all five. The logic differs for copy vs move:

* Copy — share the same control block, and increment the count (one more owner).
* Move — steal the other's control block and null it out; the count is unchanged (ownership transferred, not duplicated).

C++
// --- copy: one more owner of the same block ---
SimpleSharedPtr(const SimpleSharedPtr &other) : cb_(other.cb_)
{
    if (cb_) ++cb_->ref_cnt;
}

SimpleSharedPtr &operator=(const SimpleSharedPtr &other)
{
    if (this == &other) return *this;   // guard self-assignment
    release();                          // drop what we currently hold
    cb_ = other.cb_;
    if (cb_) ++cb_->ref_cnt;
    return *this;
}

// --- move: transfer ownership, no count change ---
SimpleSharedPtr(SimpleSharedPtr &&other) noexcept : cb_(other.cb_)
{
    other.cb_ = nullptr;                // source becomes empty
}

SimpleSharedPtr &operator=(SimpleSharedPtr &&other) noexcept
{
    if (this == &other) return *this;
    release();
    cb_ = other.cb_;
    other.cb_ = nullptr;
    return *this;
}

Two details that matter:

*  The self-assignment guard (if (this == &other)) in the assignment operators. Without it, p = p would release()the block and then try to read from it — use-after-free.
* noexcept on the move operations. Containers like std::vector will only use your move constructor during reallocation if it's noexcept; otherwise they fall back to copying. It's a real performance contract, not decoration.

With all five in place, copies and moves keep the count honest, and there are no double frees.

4. A make_shared factory with perfect forwarding

C++
template <typename T, typename... Args>
SimpleSharedPtr<T> make_simple_shared(Args &&...args)
{
    return SimpleSharedPtr<T>(new T(std::forward<Args>(args)...));
}

Three pieces of machinery are at work:

* typename... Args is a template parameter pack — make_simple_shared accepts any number of arguments of any types.
* Args &&...args are forwarding references(also called universal references). Through template type deduction, each one captures whether its argument was an lvalue or an rvalue.
* std::forward<Args>(args)... is pack expansion — the trailing ... repeats the std::forward pattern for every argument, and each std::forward preserves the original value category.

Why does forwarding matter? Inside the function, every named parameter is an lvalue. If we wrote new T(args...), every argument would be copied into T's constructor, even temporaries that could have been moved. std::forward restores the rvalue-ness:  

5. Thread safety: the count must be atomic

So far ref_cnt is a plain long. That's a latent bug the moment two threads touch the same object. Consider two threads each dropping their reference:  

Plaintext
ref_cnt is 2.
Thread A reads 2 ──┐
Thread B reads 2 ──┤  both compute 2 - 1 = 1
Thread A writes 1 ─┤  both write 1
Thread B writes 1 ─┘
ref_cnt is now 1 — but it should be 0. The object leaks forever.


The fix is std::atomic:  

C++
#include <atomic>

std::atomic<long> ref_cnt;

// Note
--cb_->ref_cnt;            // atomic read-modify-write (decrement), returns new value
++cb_->ref_cnt;            // atomic read-modify-write (increment)
cb_->ref_cnt.load();       // atomic read only

std::atomic overloads ++/--/+= as atomic operations, and .load() is an explicit atomic read.


6. weak_ptr: observing without owning

Sometimes you want to refer to an object without keeping it alive — the classic case is breaking reference cycles (a parent owns its children, children point back at the parent). If both directions were shared_ptr, the counts would never reach zero and you'd leak. weak_ptr is a non-owning observer that can tell you whether the object is still alive and hand you a temporary shared_ptr if so.  

C++
#include <iostream>
#include <memory>

struct Node {
    int id;
    std::shared_ptr<Node> next; // shared_ptr forms cycle

    Node(int val) : id(val) {
        std::cout << "Construct Node " << id << "\n";
    }
    ~Node() {
        std::cout << "Destroy Node " << id << "\n";
    }
};

void createCycleLeak() {
    // Two separate shared_ptr on stack
    auto a = std::make_shared<Node>(1);
    auto b = std::make_shared<Node>(2);

    // Create circular reference
    a->next = b;
    b->next = a;

    std::cout << "use_count(a): " << a.use_count() << "\n"; // 2
    std::cout << "use_count(b): " << b.use_count() << "\n"; // 2

    // Function scope ends, stack a & b destruct here
    std::cout << "Exiting function, stack pointers destroyed...\n";
}

int main() {
    createCycleLeak();
    std::cout << "Program exit, NO Node destructors called!\n";
    return 0;
}
Plaintext
Construct Node 1
Construct Node 2
use_count(a): 2
use_count(b): 2
Exiting function, stack pointers destroyed...
Program exit, NO Node destructors called!

The destructor ~Node() never runs — memory leak occurs.  

Step-by-Step Reference Count Breakdown

1) auto a = make_shared<Node>(1) - Heap node1 ref count = 1 (owned by stack a)
2) auto b = make_shared<Node>(2) -  Heap Node2 ref count = 1 (owned by stack b)
3) a->next = b -  Copy shared_ptr b into Node1's next → Node2 ref count +=1 → 2
4)b->next = a - 
Copy shared_ptr a into Node2's next → Node1 ref count +=1 → 2

Now,  Node1 is only held by b->next (inside Node2 Heap),   Node2 is only held by a->next (inside Node1 Heap) ,  Since both Heap memory are not release and both side are waiting other side release first then can release themself. so there is a circular dependency now.


So we need introduce a weak_ptr in our implementation,  This introduces a subtle lifetime problem. The object should die when the last shared_ptr goes away — but the control block must survive as long as any weak_ptr still points at it (a weak_ptr needs to read ref_cnt to know whether the object expired). So we need two counts:  

C++
std::atomic<long> ref_cnt;   // strong owners (shared_ptr)
std::atomic<long> weak_cnt;  // weak observers + 1 collective ref from the strong group

The clever part is the "strong group holds one weak count" convention. Instead of having both counts independently decide when to free the block (which creates a race over who frees it), we make a single rule:

* weak_cnt starts at 1— that one represents "the strong owners, collectively."
* Each weak_ptr adds 1 to weak_cnt.
* When the last strong reference dies, we destroy the object and drop that one collective weak count.
* The control block is freed only when weak_cnt reaches 0.  

This way a single counter governs the control block's lifetime, so there's no double-check race between strong and weak releases.

C++
explicit ControlBlock(T *p) : ptr(p), ref_cnt(1), weak_cnt(1) {}

// in SimpleSharedPtr::release()
if (--cb_->ref_cnt == 0)
{
    delete cb_->ptr;            // object dies when strong count hits 0
    cb_->ptr = nullptr;
    if (--cb_->weak_cnt == 0)   // drop the strong group's collective weak ref
        delete cb_;             // block dies only when no weak_ptr remains either
}

// in SimpleWeakPtr::release()
if (--cb_->weak_cnt == 0)
    delete cb_;

The SimpleWeakPtr itself is another Rule-of-Five class, but it adjusts weak_cnt instead of ref_cnt, and it can be constructed from a SimpleSharedPtr:  

C++
SimpleWeakPtr(const SimpleSharedPtr<T> &s) : cb_(s.cb_)
{
    if (cb_) ++cb_->weak_cnt;   // observe, but do NOT touch ref_cnt
}

Because it touches SimpleSharedPtr's private cb_, the two classes are friends  

7. lock(): the lock-free heart

weak_ptr::lock() is where the design earns its keep. It asks: "Is the object still alive? If so, give me a strong owner." Naively:  

C++
if (cb_->ref_cnt.load() != 0) {   // "it's alive!"
    // another thread could destroy it RIGHT HERE
    ++cb_->ref_cnt;               // resurrecting a dead object → undefined behavior
    return SimpleSharedPtr<T>(cb_);
}

The gap between the check and the increment is a race. The check and the increment must be one atomic operation. That's what compare-and-swap (CAS) provides:

C++
SimpleSharedPtr<T> lock() const
{
    if (cb_)
    {
        long count = cb_->ref_cnt.load();          // snapshot
        while (count != 0)                         // only if it looks alive
        {
            if (cb_->ref_cnt.compare_exchange_weak(count, count + 1))
                return SimpleSharedPtr<T>(cb_, true);  // success: adopt the incremented ref
            // CAS failed: `count` was refreshed with the current value — retry
        }
    }
    return SimpleSharedPtr<T>();                   // expired
}

With that, our simple smart pointer implementation is complete. Below is the full, compilable and runnable source code.

C++
#include <gtest/gtest.h>

#include <atomic>
#include <cassert>
#include <iostream>
#include <memory>
#include <utility>

namespace
{

template<typename T>
struct ControlBlock
{
    T* ptr;
    // ref_cnt: number of SimpleSharedPtr owners.
    // weak_cnt: number of SimpleWeakPtr observers, PLUS one collective
    //           reference held by the strong group while ref_cnt > 0.
    std::atomic<long> ref_cnt;
    std::atomic<long> weak_cnt;

    explicit ControlBlock(T* p):
        ptr(p),
        ref_cnt(1),
        weak_cnt(1)
    {}
};

template<typename T>
class SimpleWeakPtr; // forward declaration

template<typename T>
class SimpleSharedPtr
{
private:
    ControlBlock<T>* cb_;

    friend class SimpleWeakPtr<T>;

    // Adopt a control block whose ref_cnt has ALREADY been incremented.
    // Used by SimpleWeakPtr::lock(). The bool tag disambiguates from the
    // public T* constructor.
    SimpleSharedPtr(ControlBlock<T>* cb, bool /*adopt*/):
        cb_(cb)
    {}

    void release()
    {
        if (!cb_)
            return;

        // Drop a strong reference.
        if (--cb_->ref_cnt == 0)
        {
            // Last strong owner: destroy the managed object now...
            delete cb_->ptr;
            cb_->ptr = nullptr;

            // ...and release the strong group's collective weak count.
            // If no SimpleWeakPtr remains, this frees the control block.
            if (--cb_->weak_cnt == 0)
                delete cb_;
        }
        cb_ = nullptr;
    }

public:
    explicit SimpleSharedPtr(T* p = nullptr)
    {
        cb_ = p ? new ControlBlock<T>(p) : nullptr;
    }

    SimpleSharedPtr(const SimpleSharedPtr& other):
        cb_(other.cb_)
    {
        if (cb_)
            ++cb_->ref_cnt;
    }

    SimpleSharedPtr& operator=(const SimpleSharedPtr& other)
    {
        if (this == &other)
            return *this;

        release();
        cb_ = other.cb_;
        if (cb_)
            ++cb_->ref_cnt;
        return *this;
    }

    SimpleSharedPtr(SimpleSharedPtr&& other) noexcept:
        cb_(other.cb_)
    {
        other.cb_ = nullptr;
    }

    SimpleSharedPtr& operator=(SimpleSharedPtr&& other) noexcept
    {
        if (this == &other)
            return *this;

        release();
        cb_ = other.cb_;
        other.cb_ = nullptr;
        return *this;
    }

    ~SimpleSharedPtr()
    {
        release();
    }

    T& operator*() const
    {
        assert(cb_ && cb_->ptr && "dereference of empty SimpleSharedPtr");
        return *(cb_->ptr);
    }

    T* operator->() const
    {
        assert(cb_ && cb_->ptr && "dereference of empty SimpleSharedPtr");
        return cb_->ptr;
    }

    long use_count() const
    {
        return cb_ ? cb_->ref_cnt.load() : 0;
    }

    T* get() const
    {
        return cb_ ? cb_->ptr : nullptr;
    }

    void reset(T* p = nullptr)
    {
        release();
        cb_ = p ? new ControlBlock<T>(p) : nullptr;
    }

    explicit operator bool() const
    {
        return cb_ != nullptr;
    }
};

template<typename T>
class SimpleWeakPtr
{
private:
    ControlBlock<T>* cb_;

    friend class SimpleSharedPtr<T>;

    void release()
    {
        if (!cb_)
            return;

        // The control block is freed once no strong group and no weak
        // observers reference it (weak_cnt reaching 0 covers both).
        if (--cb_->weak_cnt == 0)
            delete cb_;
        cb_ = nullptr;
    }

public:
    SimpleWeakPtr():
        cb_(nullptr)
    {}

    SimpleWeakPtr(const SimpleSharedPtr<T>& s):
        cb_(s.cb_)
    {
        if (cb_)
            ++cb_->weak_cnt;
    }

    SimpleWeakPtr(const SimpleWeakPtr& other):
        cb_(other.cb_)
    {
        if (cb_)
            ++cb_->weak_cnt;
    }

    SimpleWeakPtr& operator=(const SimpleWeakPtr& other)
    {
        if (this == &other)
            return *this;

        release();
        cb_ = other.cb_;
        if (cb_)
            ++cb_->weak_cnt;
        return *this;
    }

    SimpleWeakPtr& operator=(const SimpleSharedPtr<T>& s)
    {
        release();
        cb_ = s.cb_;
        if (cb_)
            ++cb_->weak_cnt;
        return *this;
    }

    SimpleWeakPtr(SimpleWeakPtr&& other) noexcept:
        cb_(other.cb_)
    {
        other.cb_ = nullptr;
    }

    SimpleWeakPtr& operator=(SimpleWeakPtr&& other) noexcept
    {
        if (this == &other)
            return *this;

        release();
        cb_ = other.cb_;
        other.cb_ = nullptr;
        return *this;
    }

    ~SimpleWeakPtr()
    {
        release();
    }

    long use_count() const
    {
        return cb_ ? cb_->ref_cnt.load() : 0;
    }

    bool expired() const
    {
        return use_count() == 0;
    }

    // Atomically obtain a strong owner IF the object is still alive.
    // Uses a CAS loop so we never resurrect an object whose count hit 0.
    SimpleSharedPtr<T> lock() const
    {
        if (cb_)
        {
            long count = cb_->ref_cnt.load();
            while (count != 0)
            {
                if (cb_->ref_cnt.compare_exchange_weak(count, count + 1))
                    return SimpleSharedPtr<T>(cb_, true); // adopt incremented ref
                // count was refreshed by the failed CAS; retry.
            }
        }
        return SimpleSharedPtr<T>(); // expired
    }
};

template<typename T, typename... Args>
static SimpleSharedPtr<T> make_simple_shared(Args&&... args)
{
    return SimpleSharedPtr<T>(new T(std::forward<Args>(args)...));
}

struct TNode
{
    int id;

    TNode(int i):
        id(i)
    {
        std::cout << "Node constructing... " << id << "\n";
    }

    ~TNode()
    {
        std::cout << "Node destructing... " << id << " \n";
    }
};

}

TEST(SimpleSharedPtr, normalTest)
{
    auto p1 = make_simple_shared<TNode>(1);
    std::cout << "count: " << p1.use_count() << " \n";

    auto p2 = p1; // copy
    std::cout << "count: " << p1.use_count() << " \n";

    SimpleSharedPtr<TNode> p3 = std::move(p1); // move
    std::cout << "p2 count: " << p2.use_count() << " \n";
    std::cout << "p3 count: " << p3.use_count() << " \n";
    std::cout << "p1 empty?: " << (!p1 ? "Yes" : "No") << " \n";

    auto r1 = std::make_shared<TNode>(1);
    std::cout << "count: " << r1.use_count() << " \n";

    auto r2 = r1;
    std::cout << "count: " << r1.use_count() << " \n";

    std::shared_ptr<TNode> r3 = std::move(r1); // move
    std::cout << "r2 count: " << r2.use_count() << " \n";
    std::cout << "r3 count: " << r3.use_count() << " \n";
    std::cout << "r1 empty?: " << (!r1 ? "Yes" : "No") << " \n";
}

TEST(SimpleSharedPtr, weakPtrTest)
{
    SimpleWeakPtr<TNode> w;

    {
        auto s = make_simple_shared<TNode>(42);
        w = s; // weak observes, does not extend lifetime

        EXPECT_EQ(s.use_count(), 1); // weak does not bump strong count
        EXPECT_EQ(w.use_count(), 1);
        EXPECT_FALSE(w.expired());

        // lock() while alive yields a valid strong owner.
        auto locked = w.lock();
        EXPECT_TRUE(static_cast<bool>(locked));
        EXPECT_EQ(s.use_count(), 2); // s + locked
        EXPECT_EQ(locked->id, 42);
    } // s and locked destroyed here -> TNode destructed

    // Object is gone, but the control block survives because w still exists.
    EXPECT_TRUE(w.expired());
    EXPECT_EQ(w.use_count(), 0);

    auto dead = w.lock();
    EXPECT_FALSE(static_cast<bool>(dead)); // lock() on expired returns empty
}