skip to content

In C++, what do std::weak_ptr's lock(), expired() and conversion to std::shared_ptr each do, and which belongs in an observer list?

level: middleimportance: must knowfreq 75%

answer

  1. observes the control block
  2. empty result versus exception
  3. a snapshot can go stale
  4. owner for the full expression
  5. one weak edge breaks the cycle

basics

~20 s

lock() returns an owning std::shared_ptr, or an empty one if the object is gone; expired() only reports whether it is gone; std::shared_ptr's constructor from a weak_ptr throws std::bad_weak_ptr instead. Observer lists call lock() and use the result.

solid answer

~40 s

A `std::weak_ptr` refers to the control block without adding to the strong count, so it never keeps the object alive and cannot be dereferenced. To use the object you promote it: `lock()` returns a `shared_ptr` that owns the object for as long as that `shared_ptr` lives, or an empty one if the object is already destroyed; the standard specifies it as `expired() ? shared_ptr<T>() : shared_ptr<T>(*this)`, executed atomically. Constructing `std::shared_ptr<T>(w)` does the same but throws `std::bad_weak_ptr` when expired. `expired()` and `use_count()` are snapshots: another thread can drop the last owner right after you read them, so `if (!w.expired()) w.lock()->send()` can still dereference null. An observer list holds `weak_ptr`s, calls `lock()` per entry and skips empty results; and making one edge of a `shared_ptr` cycle weak is what lets both objects be destroyed.

code

cpp · 34 lines
cpp
#include <cstdio>
#include <memory>
#include <string>
#include <vector>

struct Room;
struct Session {
    std::string user;
    std::shared_ptr<Room> room;                       // a session keeps its room alive
    explicit Session(std::string u) : user(std::move(u)) {}
    ~Session() { std::printf("~Session %s\n", user.c_str()); }
};
struct Room {
    std::vector<std::weak_ptr<Session>> members;      // observers: must not own sessions
    ~Room() { std::puts("~Room"); }
    void broadcast(const char* text) {
        for (const auto& w : members)
            if (auto s = w.lock())                     // owner for the duration of the call
                std::printf("to %s: %s\n", s->user.c_str(), text);
            else
                std::puts("skipped a closed session");
    }
};

int main() {
    auto room = std::make_shared<Room>();
    auto ann = std::make_shared<Session>("ann");
    auto bob = std::make_shared<Session>("bob");
    ann->room = room; bob->room = room;
    room->members = {ann, bob};
    bob.reset();                                      // bob disconnects
    room->broadcast("hello");
    std::printf("room owners: %ld\n", room.use_count());
}

go deeper

for a junior

Know that a weak_ptr observes without owning and that lock() gives you a shared_ptr you must test before use.

for a middle

Explain lock() versus expired() versus the throwing constructor, and how one weak edge lets a shared_ptr cycle be destroyed.

for a senior

Find check-then-use races on expired() and use_count(), and leaks where an observer list or back-pointer was declared as shared_ptr.

for a principal

Decide which edges in a shared graph are allowed to own, and make weak back-edges the reviewed default rather than a fix after a leak.

## What a weak_ptr is `std::weak_ptr<T>` is the non-owning companion of `std::shared_ptr<T>`. It is created from a `shared_ptr` (or another `weak_ptr`), points at the same control block, and increments only the **weak** count. Because it does not own, it offers no `operator*` or `operator->`: the only way to reach the object is to promote the `weak_ptr` to a `shared_ptr` first. That design makes it impossible to use the object without holding ownership during the use. ## The members and what each one promises | member | returns | if the object is gone | |---|---|---| | `lock()` | a `shared_ptr<T>` | an empty `shared_ptr` | | `std::shared_ptr<T>(w)` | a `shared_ptr<T>` | throws `std::bad_weak_ptr` | | `expired()` | `bool` | `true` | | `use_count()` | number of owners | `0` | | `reset()` | nothing | — (stops observing) | The standard specifies `lock()` as `expired() ? shared_ptr<T>() : shared_ptr<T>(*this)`, **executed atomically**: the check and the promotion cannot be separated by another thread's release. `expired()` and `use_count()` have no such guarantee across calls; each is a snapshot that may be stale by the next line. ## Why lock() and not expired() before use ```cpp if (!w.expired()) // true now ... w.lock()->send(msg); // ... but the last owner may be gone here ``` Between the two calls another thread can drop the last `shared_ptr`, and `lock()` then returns an empty pointer that is dereferenced. The fix is to promote once and test the result: ```cpp if (auto s = w.lock()) // s owns the session for the whole block s->send(msg); ``` The temporary from `w.lock()->send(msg)` would also keep the object alive until the end of the full expression; the danger is only the empty case. `expired()` is still the right tool for **cleanup** — erasing dead entries from an observer list — where acting on a slightly stale answer does no harm. ## An observer list in a chat server A chat room keeps the sessions it should broadcast to, but must not keep a disconnected session alive. Its list therefore holds `std::vector<std::weak_ptr<Session>>`: 1. `broadcast` walks the list, calls `lock()` on each entry and sends through the resulting `shared_ptr`; 2. an empty result means the session closed, so the entry is skipped (and can be erased); 3. while a send is in progress, the local `shared_ptr` keeps that session alive even if its connection closes on another thread. ## Breaking a shared_ptr cycle If `Session` holds `std::shared_ptr<Room>` and `Room` holds `std::vector<std::shared_ptr<Session>>`, each keeps the other's strong count above zero. When the server drops its own pointers, nothing outside references the pair, yet neither destructor ever runs: the example on this page prints no `~Session` and no `~Room` in that version. Making the room's edge weak breaks the cycle — the session owns its room, the room only observes its sessions — and both destructors run as soon as the outside owners go. The rule of thumb in C++ code: the edge that points "up" or "back" (to a parent, an owner, a registry that must not pin) is the `weak_ptr`. ## What a weak_ptr still keeps alive A `weak_ptr` does not keep the **object** alive, but it does keep the **control block** alive, because it must be able to answer `expired()` later. When the object was created with `std::make_shared`, its storage lives inside that block, so an observer list full of stale `weak_ptr`s pins the storage of every closed session until the entries are erased. Sweeping dead entries regularly is therefore part of using `weak_ptr` well, not just tidiness. ## Promoting inside a loop When a loop sends to many observers, promote each entry once, use the local `shared_ptr` for the whole iteration, and let it go at the end of the iteration. Holding the promoted pointers longer — collecting them into a vector "to send later" — quietly turns observers back into owners for that period, which is sometimes what you want (a consistent snapshot of recipients) and sometimes a delayed destruction nobody expected. ## Lookups keyed by weak_ptr A `weak_ptr` has no `operator<` or hash of its own, because its stored pointer may refer to a destroyed object. Ordered containers keyed by `weak_ptr` use `std::owner_less`, which compares control blocks through `owner_before`, so the ordering stays valid after the object dies. ## Common mistakes - Dereferencing a `weak_ptr` directly — it does not compile. - Testing `expired()` and then calling `lock()` as if the answer still held. - Making both edges of a cycle weak, so nothing owns either object. - Reading `use_count() == 1` as proof that no other thread can gain ownership; any `weak_ptr` holder can `lock()` at any moment.

  • When would you construct std::shared_ptr from a weak_ptr instead of calling lock()?
    When an expired object means a bug rather than a normal event. The constructor throws `std::bad_weak_ptr`, so the failure surfaces as an exception at the point of promotion; `lock()` returns an empty `shared_ptr` that the caller must test. Observer lists and caches expect expiry and use `lock()`.
  • How do you remove dead entries from a std::vector<std::weak_ptr<Session>>?
    Erase the entries whose `expired()` returns true, for example with `std::erase_if` (C++20) or the erase-remove idiom. Here a stale answer is harmless: an entry that expires just after the check is removed on the next sweep. That is why `expired()` suits cleanup even though it is the wrong guard before use.

  • Checking expired() first makes the result of lock() safe to dereference
  • A weak_ptr can be dereferenced directly with * or ->
  • Breaking a cycle means making both edges weak
  • Objects caught in a shared_ptr cycle are destroyed at program exit anyway
  • use_count() == 1 means no other thread can gain ownership