C++ · Module 11 · Lesson 31 min read

shared_ptr & weak_ptr

std::shared_ptr — shared ownership

ini
auto p1 = std::make_shared<Group>("Trip to Pokhara");
auto p2 = p1;                // copy: both own it, count = 2
p1.use_count();              // 2
  • Keeps a reference count in a "control block"
  • Copying increments it, destroying/resetting decrements it
  • When it reaches 0, the object is deleted
  • The count is thread-safe (atomic); the object itself is not

make_shared ✅

Allocates the object and control block together — one allocation instead of two, faster.

Costs

  • Twice the size of a raw pointer (object pointer + control block pointer)
  • Atomic increments/decrements on every copy → Use unique_ptr by default; shared_ptr only for genuinely shared ownership.

The cycle problem ⚠️

c
struct Person { std::shared_ptr<Person> friend_; };
a->friend_ = b; b->friend_ = a;    // each keeps the other alive → LEAK

Counts never reach zero.

std::weak_ptr — non-owning observer

arduino
std::weak_ptr<Group> w = p1;   // doesn't increase the count
if (auto locked = w.lock()) {  // get a shared_ptr if the object still exists
    locked->name();
} else {
    // already deleted
}
w.expired();                    // true if the object is gone

Use it for back-references (child → parent), observers, and caches.

Typical design

  • Parent owns children: std::vector<std::shared_ptr<Child>> (or unique_ptr)
  • Child refers back to parent: std::weak_ptr<Parent>

Passing shared_ptr ✅

  • Function just uses the object → pass T& or const T& (no count change)
  • Function will store a copy → take std::shared_ptr<T> by value
  • Avoid passing const std::shared_ptr<T>& unless you need to inspect the pointer itself

Example

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

struct Group;

struct Member {
    std::string name;
    std::weak_ptr<Group> group;          // back-reference: does not own
    explicit Member(std::string n) : name(std::move(n)) {}
    ~Member() { std::cout << "  - member " << name << '\n'; }
};

struct Group : std::enable_shared_from_this<Group> {
    std::string title;
    std::vector<std::shared_ptr<Member>> members;     // owns its members
    explicit Group(std::string t) : title(std::move(t)) {}
    ~Group() { std::cout << "  - group " << title << '\n'; }
    void add(const std::string& name) {
        auto m = std::make_shared<Member>(name);
        m->group = shared_from_this();
        members.push_back(m);
    }
};

struct BadNode {                          // cycle with shared_ptr: never freed
    std::shared_ptr<BadNode> other;
    ~BadNode() { std::cout << "  - BadNode (never printed if leaked)\n"; }
};

int main() {
    std::shared_ptr<Member> survivor;
    {
        auto trip = std::make_shared<Group>("Pokhara trip");
        std::cout << "use_count after create: " << trip.use_count() << '\n';
        {
            auto view = trip;             // a second owner
            std::cout << "use_count with a copy: " << trip.use_count() << '\n';
        }
        std::cout << "use_count after the copy is gone: " << trip.use_count() << '\n';

        trip->add("Asha");
        trip->add("Ravi");
        survivor = trip->members[0];      // keep one member alive beyond the group
        if (auto g = survivor->group.lock())
            std::cout << survivor->name << " belongs to " << g->title << '\n';
        std::cout << "leaving the group's scope...\n";
    }
    std::cout << "group expired? " << std::boolalpha << survivor->group.expired() << '\n';
    std::cout << survivor->name << " still exists (we hold a shared_ptr)\n";

    {
        auto a = std::make_shared<BadNode>();
        auto b = std::make_shared<BadNode>();
        a->other = b;
        b->other = a;
        std::cout << "cycle created: a count " << a.use_count() << ", b count " << b.use_count() << '\n';
        b->other.reset();                 // break the cycle by hand (a weak_ptr would avoid this)
    }
    std::cout << "end of main\n";
    return 0;
}

/* Output:
use_count after create: 1
use_count with a copy: 2
use_count after the copy is gone: 1
Asha belongs to Pokhara trip
leaving the group's scope...
  - group Pokhara trip
  - member Ravi
group expired? true
Asha still exists (we hold a shared_ptr)
cycle created: a count 2, b count 2
  - BadNode (never printed if leaked)
  - BadNode (never printed if leaked)
end of main
  - member Asha
*/