Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 171 Β· Pointers, References and Memory

Smart Pointers: shared_ptr and weak_ptr

Learn C++ std::shared_ptr and std::weak_ptr - shared ownership, make_shared, reference counts, breaking cycles with weak_ptr, costs, and choosing a smart pointer.

Sometimes an object doesn't have one obvious owner. A texture might be used by several game objects, and it should stay loaded as long as any of them needs it. A network session might be referenced by the connection handler, a timer and a logging task, each of which may finish first. For these cases C++ offers std::shared_ptr<T>: a smart pointer that allows many owners and destroys the object when the last owner goes away.

shared_ptr does this by keeping a reference count next to the object: every copy of the pointer increments it, every destroyed copy decrements it, and when it reaches zero the object is deleted. Its companion, std::weak_ptr<T>, observes a shared object without owning it, which is how you break ownership cycles and build caches. This lesson covers both, plus make_shared, the real costs of shared ownership, common traps like shared_ptr cycles and this, and a clear guide for choosing between unique_ptr, shared_ptr, weak_ptr and raw pointers. Read std::unique_ptr first: it's the default, and shared ownership is the exception.

Shared ownership and the reference count

Create a shared object with std::make_shared<T>(args...) from <memory>. Copy the shared_ptr to add an owner; use_count() tells you how many owners there are right now.

C++ Watching the reference count

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The texture loads once, survives the inner block because grass still owns it, and unloads exactly when the last owner (moved) is reset. Moving a shared_ptr doesn't touch the count, which makes it cheaper than copying; copy only when you really want another owner.

use_count() is handy for learning and debugging, but don't base program logic on it. In multithreaded code the value can change the instant after you read it.

make_shared vs shared_ptr(new T)

A shared_ptr needs two things on the heap: the object, and a control block holding the reference counts (and the deleter). std::make_shared allocates both in one block of memory; std::shared_ptr<T>(new T(...)) makes two allocations, one for the object and one for the control block.

So make_shared is faster, uses less memory and has better cache locality. Prefer it for the same reasons as make_unique: no raw new, no repeated type name. Use the constructor form only when you need a custom deleter, or when you're adopting a pointer from code you don't control.

One subtle consequence: with make_shared, the object's memory is freed only when the control block is freed, which waits for every weak_ptr too (see below). For huge objects observed by long-lived weak pointers, the separate-allocation form releases the big memory sooner. That's a rare optimization; the default is still make_shared.

You can also convert a unique_ptr into a shared_ptr by moving it: std::shared_ptr<T> shared = std::move(unique);. That makes unique_ptr the perfect return type for factories: callers who want shared ownership can upgrade, and the others pay nothing.

Sharing an object between owners

Here's the kind of situation where shared ownership is the honest model: several independent components hold the same object, and none of them knows who will finish last.

C++ Several components sharing one logger

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The constructor takes the shared_ptr by value and moves it into the member. That's the standard idiom for a function that will store a shared pointer: the caller copies once (or moves, if it's done with its handle), and no extra count changes happen inside.

When a function only uses the object, take Logger& or const Logger& instead, exactly as with unique_ptr. Passing std::shared_ptr<T> by value to a function that doesn't keep it costs two atomic count updates per call for nothing.

The costs of shared_ptr

Shared ownership is convenient, but it isn't free:

  • Size: a shared_ptr holds two pointers (to the object and to the control block): 16 bytes on 64-bit systems, versus 8 for unique_ptr.
  • Atomic counting: the reference count is updated with atomic operations so that copies in different threads are safe. Atomics are much slower than ordinary increments, especially when many threads touch the same count.
  • Extra allocation: the control block (combined with the object when you use make_shared).
  • Unclear lifetimes: when anyone can extend an object's life, it's harder to know when destructors run. Overusing shared_ptr is a design smell: it often means nobody decided who owns what.
C++ Sizes and costs side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

"Thread-safe" applies only to the reference count. Two threads may copy and destroy their own shared_ptrs to the same object safely, but the object itself isn't protected: concurrent writes to *p still need a mutex. And two threads writing the same shared_ptr variable is a data race; C++20's std::atomic<std::shared_ptr<T>> handles that case.

Cycles: when shared_ptr leaks

Reference counting has one blind spot. If object A owns a shared_ptr to B and B owns a shared_ptr to A, each keeps the other's count above zero. When your last outside pointer goes away, neither count reaches zero, and both objects leak, destructors never run.

C++ A shared_ptr cycle that never gets freed

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each person has two owners (the local variable and the partner). Leaving the block removes one owner each, so both counts stay at 1 forever. Cycles happen easily in graphs, parent/child trees, observer lists and objects that store callbacks capturing a shared_ptr to themselves.

weak_ptr: observing without owning

A std::weak_ptr<T> points at an object managed by shared_ptr but doesn't count as an owner. It can tell you whether the object still exists, and it can give you temporary ownership if it does:

  • weak.lock() returns a shared_ptr<T>: a new owner if the object is alive, or an empty pointer if it's gone. This is the safe way to use a weak pointer.
  • weak.expired() returns true if the object has been destroyed. (In multithreaded code, prefer lock(), because the object could die right after expired() returns false.)

You can't dereference a weak_ptr directly. You must lock() it, which prevents the object from disappearing while you use it.

To fix the cycle, decide which direction is "owning" and make the other one weak. In a tree, parents own children (shared_ptr or, better, unique_ptr), and children point back to their parent with a weak_ptr or a raw pointer.

C++ Breaking the cycle with weak_ptr

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Now root has just one owner (the local variable), so when the block ends it's destroyed, which destroys its children vector, which destroys the child nodes. The observer notices: expired() becomes true and lock() returns null.

A cache built on weak_ptr

weak_ptr is also the natural tool for a cache that doesn't keep things alive. The cache remembers objects for as long as someone else is using them; once the last user lets go, the cache entry simply expires.

C++ A weak_ptr cache that reuses live objects

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The image is decoded once while in use, freed as soon as nobody needs it, and decoded again on demand. (A production cache would also remove expired entries from the map now and then.) The weak_ptr is what makes this possible: a shared_ptr in the map would keep every image alive forever.

shared_from_this: a shared_ptr to yourself

Inside a member function, this is a raw pointer. If an object managed by shared_ptr needs to hand out a shared_ptr to itself (say, to register itself with a scheduler that will call it later), never write std::shared_ptr<T>(this). That creates a second, independent control block, and the object gets deleted twice.

Instead, derive from std::enable_shared_from_this<T> and call shared_from_this():

C++
class Session : public std::enable_shared_from_this<Session> {
public:
    void start(Scheduler& scheduler) {
        scheduler.later([self = shared_from_this()] {   // keeps the session alive
            self->on_timer();
        });
    }
    void on_timer();
};

auto session = std::make_shared<Session>();   // must already be owned by a shared_ptr
session->start(scheduler);

shared_from_this() only works when the object is already owned by a shared_ptr; on an object created any other way it throws std::bad_weak_ptr (since C++17). In C++17 and later there's also weak_from_this(), for callbacks that shouldn't keep the object alive.

Choosing the right pointer

You want… Use
One clear owner (the common case) std::unique_ptr<T> via make_unique
Several owners, last one cleans up std::shared_ptr<T> via make_shared
To observe a shared object that may disappear, or to break a cycle std::weak_ptr<T>
To use an object you don't own, which outlives the use T&, or T* if it can be null
A collection of values std::vector<T> or another container, no pointers at all

Start with values and unique_ptr. Reach for shared_ptr when the ownership really is shared, not because it's easier to type than thinking about lifetimes. Many large C++ codebases use unique_ptr for nearly everything and shared_ptr only in a few places like caches, asynchronous callbacks and shared immutable data.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. auto a = std::make_shared<int>(1); auto b = a; auto c = std::move(b); What is a.use_count()?

    b was a copy (2 owners), then c took b's ownership by moving, which doesn't change the count. a and c are the owners, so the count is 2.
  2. 2. Why does make_shared usually beat shared_ptr<T>(new T)?

    One allocation instead of two means less memory and better speed. The pointer is still 16 bytes, and the object itself is never automatically thread-safe.
  3. 3. Two objects each hold a shared_ptr to the other, and all outside pointers are gone. What happens?

    Each object keeps the other's count at 1, so neither count reaches zero. Make one of the links a weak_ptr to break the cycle.
  4. 4. What is the correct way to use the object behind a std::weak_ptr w?

    weak_ptr can't be dereferenced. lock() returns a shared_ptr that keeps the object alive while you use it, or an empty pointer if it's gone.
  5. 5. Inside a member function of a class managed by shared_ptr, what is wrong with std::shared_ptr<Session>(this)?

    A new shared_ptr from a raw pointer starts its own count. Derive from enable_shared_from_this and call shared_from_this() instead.

Summary

  • std::shared_ptr<T> allows many owners; a reference count in a control block deletes the object when the last owner goes away.
  • Create with std::make_shared<T>(args...) (one allocation). Copying adds an owner; moving transfers one without changing the count.
  • Costs: 16-byte pointers, atomic count updates, a control block and harder-to-follow lifetimes. Only the count is thread-safe, not the object.
  • Store a shared pointer by taking it by value and moving it into place; functions that only use the object take T&.
  • shared_ptr cycles leak. Break them with std::weak_ptr, which observes without owning; use it through lock().
  • weak_ptr is ideal for back-pointers, observers and caches that shouldn't keep objects alive.
  • Never wrap this in a new shared_ptr; use enable_shared_from_this.
  • Default to unique_ptr; use shared_ptr only when ownership is genuinely shared.

Next: Memory Layout: Stack, Heap and Objects, where you'll see where all these objects actually live and how big they are.