Observer
What you will learn on this page
Section titled “What you will learn on this page”- The problem Observer solves, shown before the pattern is named: one object changes, and a changing set of other objects must be told.
- How to decide what the subject knows, what each listener knows, and why the subscription itself deserves a class.
- The two lifetime questions every C++ Observer must answer: who outlives whom, and what may change while listeners are being told.
- A safe design: an RAII subscription handle that unsubscribes when it is destroyed, and a notification loop that survives listeners unsubscribing, subscribing, and even throwing in the middle of it.
- When direct calls are better, and why threads make this much harder.
The problem
Section titled “The problem”A trading-floor dashboard receives price changes from an exchange, one at a time, on the app’s main thread. Several parts of the dashboard care about them, and more are added every few months.
Requirements:
- FR-1 The price feed receives each update (a symbol and a price) and tells every part of the app that is interested.
- FR-2 Parts of the app start and stop listening while the app runs (a chart window opens, then closes). Adding a new kind of listener must not change the feed.
- FR-3 Listeners are told in the order they started listening.
- FR-4 A price alert fires once, when a symbol falls below a price, and then stops listening. It stops from inside its own reaction to the update.
- FR-5 A listener that has been destroyed is never called again, even if someone forgot to stop it listening.
Non-functional requirement:
- NFR-1 Single-threaded: updates arrive and are handled on one thread.
Text description of the diagram
A solid arrow is a flow of data and a dashed arrow means “uses”. The exchange connection sends price updates to the price feed. The feed tells the price board, the trade log, the drop alert (until it fires), and a chart window that is added later (while it is open).
Diagram source (Mermaid)
flowchart LR
EX["exchange connection"] -->|"price updates"| FEED["price feed"]
FEED -.->|tells| BOARD["price board"]
FEED -.->|tells| LOG["trade log"]
FEED -.->|"tells, until it fires"| ALERT["drop alert"]
FEED -.->|"tells, while open"| CHART["chart window<br/>added later"]Where Observer shows up in requirements. Listen for “when X changes, tell…”, “notify”, “subscribe”, “whoever is interested”, “listeners”, “events”, and “the list of who to tell keeps growing”. In code, the signal is a class that calls three unrelated classes by name every time it changes, and keeps gaining constructor parameters as more are added. Observer comes up often in user interfaces, event-driven code, and anywhere a model must keep several views up to date; MVC, MVP, and MVVM shows three ways a screen uses it.
The straightforward solution
Section titled “The straightforward solution”The first version calls each listener by name:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The first version, before Observer. Three listener classes, each with its// own differently named function, and a Ticker that knows all three.
// Shows the latest price of each symbol. `final` means no class can derive// from it.class PriceBoard final {public: // latest_[symbol] finds the symbol's entry, or adds one if the symbol is // new, and the assignment overwrites the old price with the new one. void show(const PriceUpdate& update) { latest_[update.symbol] = update.cents; } std::string line() const; // "ACME 99.50 | BOLT 20.00"private: // Symbol to latest price in cents. A std::map keeps its keys sorted, so // line() lists the symbols in alphabetical order. std::map<std::string, int> latest_;};
// Keeps one line of text, such as "ACME 99.50", for every update.class TradeLog final {public: void record(const PriceUpdate& update); // Returns a const reference: the caller reads the lines without copying // them, and cannot change them. const std::vector<std::string>& lines() const { return lines_; }private: std::vector<std::string> lines_;};
// Watches one symbol and records a message the first time its price falls// below `below_cents`. It cannot stop being called, so after it fires it// keeps a message and ignores every later update itself.class DropAlert final {public: DropAlert(std::string symbol, int below_cents); void check(const PriceUpdate& update); // Empty (std::nullopt) until the alert fires; then the message text. const std::optional<std::string>& message() const { return message_; }private: std::string symbol_; int below_cents_; std::optional<std::string> message_; // set once; after that, check does nothing};
// The ticker calls every listener by name. It is handed the three listeners// when it is built and keeps a reference to each (it owns none of them), so// the set of listeners is fixed for the ticker's whole life: nothing can// join later, and nothing can leave. The listeners must outlive the ticker.class Ticker final {public: // The `: board_{board}, ...` part is the member initializer list: it // binds each reference member to the object passed in. A reference must // be bound when it is created, so this is the only place to do it. Ticker(PriceBoard& board, TradeLog& log, DropAlert& alert) : board_{board}, log_{log}, alert_{alert} {} void publish(const PriceUpdate& update);private: PriceBoard& board_; TradeLog& log_; DropAlert& alert_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Passes one update to each listener, always in this fixed order. Each// listener has its own function name (show, record, check), so the ticker// must know every listener's type to call it.void Ticker::publish(const PriceUpdate& update) { board_.show(update); log_.record(update); alert_.check(update); // a fourth listener means a fourth line, a fourth // member, and a new constructor parameter}It works, and it is easy to follow:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records// a failure, and prints both values, if they are not equal. They come from// the site's small test header, lld_test.hpp.//// The ticker works; every listener is wired in by name.// Set-up: one board, log, and alert (watching ACME below 100.00), all// handed to the ticker. Two ACME prices, both below 100.00, are published.// Proves: the board kept the latest price, the log has both lines, and the// alert's message describes the first drop, not the second.LLD_TEST(before_the_ticker_calls_each_listener_it_was_built_with) { before::PriceBoard board; before::TradeLog log; before::DropAlert alert{"ACME", 10'000}; before::Ticker ticker{board, log, alert}; ticker.publish({"ACME", 9'950}); ticker.publish({"ACME", 9'800}); LLD_CHECK_EQ(board.line(), std::string{"ACME 98.00"}); LLD_CHECK_EQ(log.lines().size(), std::size_t{2}); // Still called after it fired; its own flag keeps it quiet. LLD_CHECK_EQ(alert.message().value_or(""), std::string{"ACME fell below 100.00: 99.50"});}But it fails two of the requirements, and has a third problem:
- FR-2 fails. The set of listeners is fixed when the
Tickeris built. A chart window that opens later cannot join, and adding a fourth kind of listener means a new member, a new constructor parameter, a new line inpublish, and a change to every place that creates aTicker. - FR-4 is faked. The alert cannot stop listening, so it keeps a flag and ignores updates forever after it fires.
- The ticker depends on every listener. Its header includes them all, and a test of the ticker needs a real board, log, and alert.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”For each piece of data, ask: whose is it?
| Data | It is about | So it belongs to |
|---|---|---|
| the latest price per symbol | what the board shows | the board |
| the lines written so far | the log | the log |
| symbol, threshold, the message | one alert | that alert |
| who is listening, in what order | the feed’s audience | the feed |
| “this listener is listening to that feed” | one relationship | a subscription object |
The last row is the new idea. Starting to listen creates a relationship between two objects that have their own lifetimes. Somebody must end it when either side goes away. In C++, a thing that must be ended reliably is a resource, and a resource gets an RAII class.
Then, for each function, ask: who knows enough to do it?
| Function | Who knows enough | So it belongs to |
|---|---|---|
| react to one update | each listener, about itself | each listener, as one function |
| tell everyone, in order | the feed | the feed (publish) |
| start listening | the feed (it keeps the list) | the feed (subscribe) |
| stop listening | the relationship | the subscription (cancel, or its destructor) |
| decide who listens to what | the code that builds the app | main, or the window that opens |
Every listener has the same single job, so they share one interface, and the feed calls only that.
The pattern
Section titled “The pattern”That is the Observer pattern. The changing object is often called the subject or publisher, and the listeners observers or subscribers.
| Role | What it does | In this example |
|---|---|---|
| Subject | Keeps the list of listeners and tells them about each change | PriceFeed |
| Observer interface | The one function every listener provides | PriceListener::on_price |
| Concrete observers | React to changes in their own way | PriceBoard, TradeLog, DropAlert |
| Subscription (C++) | Owns one listener’s place in the list; unsubscribes when destroyed | Subscription |
The subscription is not part of the classic description of the pattern, which only says that observers attach and detach. In C++ it is the part that makes the pattern safe, as the next section shows.
class PriceFeed final
the subject
Data members
std::shared_ptr<ListenerList> listeners_;never null; handles watch it through weak_ptr
Member functions
Subscription subscribe(PriceListener& listener);[[nodiscard]]void publish(const PriceUpdate& update);std::size_t listener_count() const;
class Subscription final
move-only RAII handle
Data members
std::weak_ptr<ListenerList> list_;does not keep the list alivestd::size_t id_;which entry is ours
Member functions
void cancel() noexcept;also run by the destructorbool active() const noexcept;
interface (abstract class) PriceListener
not copyable or movable
Member functions
virtual void on_price(const PriceUpdate& update) = 0;
class PriceBoard final
a PriceListener
Data members
std::map<std::string, int> latest_;
class TradeLog final
a PriceListener
Data members
std::vector<std::string> lines_;
class DropAlert final
a PriceListener
Data members
std::string symbol_;int below_cents_;std::optional<std::string> message_;Subscription subscription_;its own; declared last
Text description of the diagram
A solid arrow means “owns”, a dashed arrow means “uses”, and a thick arrow means “implements”. PriceFeed (the subject) owns the ListenerList, which holds an id and a listener for each entry, in order. A Subscription, holding one entry’s id, watches the list through a weak_ptr. The list points at each listener through the PriceListener interface, and the feed calls on_price through it. PriceBoard, TradeLog, and DropAlert implement PriceListener. DropAlert owns its own Subscription, and main owns the board, the log, and their subscriptions.
Diagram source (Mermaid)
flowchart TB
FEED["PriceFeed<br/>subject"] -->|owns| LIST["ListenerList<br/>id and listener, in order"]
SUB["Subscription<br/>one entry's id"] -.->|"watches, weak_ptr"| LIST
LIST -.->|"points at"| PL["PriceListener<br/>interface"]
FEED -.->|"calls on_price"| PL
BOARD["PriceBoard"] ==>|implements| PL
LOG["TradeLog"] ==>|implements| PL
ALERT["DropAlert"] ==>|implements| PL
ALERT -->|owns| SUB
MAIN["main"] -->|"owns the board, the log,<br/>and their subscriptions"| SUBThe naive version, and its two lifetime bugs
Section titled “The naive version, and its two lifetime bugs”The shortest Observer stores a pointer to each listener:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED: the shortest possible subject. It stores the address of each// attached listener and calls them all in publish. Nothing ties a// listener's lifetime to its place in the list, and nothing protects the// loop in publish from a listener that changes the list. Both mistakes// compile cleanly; they show up only at run time, as undefined behaviour.class NaiveFeed final {public: // Stores the listener's address. The caller must remember to call // detach before the listener is destroyed; nothing makes them. void attach(PriceListener& listener) { listeners_.push_back(&listener); } // std::erase (C++20) removes every element equal to this address. The // elements after it move one place towards the front, so the vector // gets shorter and every later element changes index. void detach(PriceListener& listener) { std::erase(listeners_, &listener); } void publish(const PriceUpdate& update) { // A range-for works out begin() and end() once, before the first // pass, and then just steps an iterator from one to the other. If // the vector changes during the loop, those saved iterators no // longer describe it (they are "invalidated"). for (PriceListener* listener : listeners_) { // iterators into listeners_ // If the listener has been destroyed, this calls through a // dangling pointer: undefined behaviour (first bug, below). listener->on_price(update); } }private: std::vector<PriceListener*> listeners_; // owns nothing; knows nothing of lifetimes};It compiles without warnings with this site’s flags, and it has two bugs that appear only when lifetimes change.
These are the two questions any C++ Observer must answer:
- Who outlives whom? The feed points at listeners it does not own. Something must guarantee that a listener leaves the list before it is destroyed, and that leaving is safe even if the feed is already gone.
- What may change during a notification? A listener’s reaction
may unsubscribe itself (FR-4), unsubscribe another, subscribe a new
one, publish again, or throw. The loop in
publishmust survive each of these with a rule you can state.
The C++ implementation
Section titled “The C++ implementation”The update and the listener interface
Section titled “The update and the listener interface”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One price change, as the exchange reports it. A plain struct: just two// public pieces of data, no behaviour. Prices are whole cents in an int, not// a double, so 99.50 is stored exactly as 9950 with no rounding error.struct PriceUpdate { std::string symbol; // e.g. "ACME" int cents = 0; // the new price, in cents};
// Formats cents as "101.50": whole units, a dot, then always two digits,// so 2000 becomes "20.00" and 9905 becomes "99.05". Written for prices,// which are never negative.std::string money(int cents);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Anything that wants to hear about price changes: the observer interface.// The feed only knows this type, never PriceBoard or TradeLog, so a new// kind of listener needs no change to the feed.class PriceListener {public: // Virtual, so destroying a listener through a PriceListener pointer or // reference runs the destructor of the real (derived) class too. virtual ~PriceListener() = default; // `= 0` makes this pure virtual: PriceListener has no body for it, and // every concrete listener must write its own (marked `override`). The // feed calls it once per update; the listener decides what it means. virtual void on_price(const PriceUpdate& update) = 0;
// The feed knows each listener by its address, so a listener is never // copied or moved: a copy would have a different address. PriceListener(const PriceListener&) = delete; PriceListener& operator=(const PriceListener&) = delete;
protected: // Protected: only a derived class can construct a PriceListener, so // nobody can try to make a bare "listener of nothing". PriceListener() = default;};The feed finds listeners by address, so a listener is an object
with identity, like an entity: a copy at a different address would be a
different listener that nobody subscribed. Deleting the copy operations
in the interface makes every listener class non-copyable and, because
declaring them suppresses the implicit move operations, non-movable
too. A test checks this with static_assert.
The subscription handle
Section titled “The subscription handle”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Proof that a listener is subscribed. Destroying it, or calling cancel,// unsubscribes. Safe to cancel twice, during a notification, or after// the feed itself is gone.//// The idea is RAII ("resource acquisition is initialization"): the handle// holds one place in the feed's list, and its destructor gives the place// back, so the place cannot be forgotten on an early return or exception.// The handle remembers the list (weakly) and the entry's id number; it// never touches the listener itself.class Subscription final {public: Subscription() = default; // subscribed to nothing // Move-only: moving hands the place to a new handle and leaves the old // one empty, so exactly one handle owns each place. A copy would mean // two handles cancelling one place, so copying is deleted. noexcept: // moving cannot throw (a weak_ptr move and a number copy). Subscription(Subscription&& other) noexcept; Subscription& operator=(Subscription&& other) noexcept; Subscription(const Subscription&) = delete; Subscription& operator=(const Subscription&) = delete; // The RAII step: when the handle goes out of scope, it unsubscribes. ~Subscription() { cancel(); }
// Unsubscribes now, if still subscribed; afterwards the handle is empty. void cancel() noexcept; // True while this handle still holds a place: it has not been cancelled // or moved from, and the feed's list still exists. expired() is true // when the weak_ptr is empty or the list it pointed at is gone. bool active() const noexcept { return !list_.expired(); }
private: // Only PriceFeed may use the private constructor below, so the only way // to get a live Subscription is PriceFeed::subscribe. friend class PriceFeed; Subscription(std::weak_ptr<ListenerList> list, std::size_t id) noexcept : list_{std::move(list)}, id_{id} {}
// A std::weak_ptr points at an object owned by a std::shared_ptr // without owning it. It can be asked "is it still there?" (expired) and // turned into a shared_ptr for a moment (lock), which is null if the // object is gone. So the handle never dangles, even if the feed dies. std::weak_ptr<ListenerList> list_; // does not keep the feed's list alive std::size_t id_ = 0; // which entry in the list is this handle's};This answers the first question. Whoever holds a Subscription holds
the listener’s place in the list, and when the handle is destroyed, the
place is given up, the same way a std::unique_ptr gives up its
memory. It is move-only, so there is always exactly one owner of
each place, and subscribe is [[nodiscard]], because a handle that is
thrown away unsubscribes at once.
The handle holds a std::weak_ptr to the feed’s list, not a pointer to
the feed. If the feed is destroyed first, the list dies with it, the
weak_ptr expires, and cancel finds nothing to do. Nobody else keeps
the list alive beyond a single cancel call (whose lock() shares
ownership just long enough to mark the entry); the std::shared_ptr in the feed exists only so the
handles can ask “is it still there?” safely.
The feed
Section titled “The feed”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Tells every subscribed listener about each price change, in the order// they subscribed. Single-threaded. This is the subject: it keeps a list// of listeners it does not own, and knows them only as PriceListener.class PriceFeed final {public: // Creates the (empty) listener list. Defined in price_feed.cpp. PriceFeed(); PriceFeed(const PriceFeed&) = delete; // subscriptions refer to this feed's list PriceFeed& operator=(const PriceFeed&) = delete;
// Adds the listener at the end of the list and returns the handle that // keeps it there. The listener must outlive the returned Subscription. // [[nodiscard]]: a result that is ignored is destroyed at once, and that // unsubscribes straight away, so the compiler warns about it. [[nodiscard]] Subscription subscribe(PriceListener& listener); // Calls on_price(update) on every subscribed listener, in order. If a // listener throws, the exception leaves publish and the rest of the // listeners are not told about this update. void publish(const PriceUpdate& update); // How many listeners are subscribed (cancelled entries not counted). std::size_t listener_count() const;
private: // The feed is the only owner of the list. It is held by shared_ptr // only so that Subscription handles can watch it through weak_ptr and // notice when it is gone. ListenerList is only declared in the header // (subscription.hpp); its definition is private to price_feed.cpp. std::shared_ptr<ListenerList> listeners_; // never null};The feed cannot be copied: a copy would share one list between two
feeds, and every handle would refer to both. Deleting the copy
operations also stops the compiler from generating moves, so the feed
cannot be moved either, and that keeps the “never null” comment true: a
moved-from feed would have a null listeners_. The comment on subscribe
is the one rule the caller must keep: the listener must outlive its
subscription. The listeners below keep it by holding their own
subscription, and main keeps it by declaring each subscription after
its listener, so it is destroyed first.
Local objects are destroyed in reverse order of declaration, so when
main returns, the objects from the first snippet in the Check section below go in this order:
alert (its own subscription first, since it is declared last inside
it), log_subscription, log, board_subscription, board, and
finally feed. Every subscription goes before its listener. (The
survivor and outlived objects of the second snippet are declared
later, so they go before all of these.)
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The feed's list of listeners. A cancelled entry is only marked during a// notification, and removed when the outermost notification ends, so the// loop in publish never sees the vector change under it.// Its members are public because only this file can see the class: the// feed, the Round guard, and Subscription::cancel are its only users.class ListenerList {public: // One subscribed listener. The id is the number the Subscription handle // remembers; ids are never reused, so an old handle cannot cancel // someone else's entry. struct Entry { std::size_t id; PriceListener* listener; // null once cancelled };
std::vector<Entry> entries; // in subscription order, the order of calls std::size_t next_id = 1; // the id the next subscribe will hand out int depth = 0; // how many publish calls are running (nested ones count)
// Called by Subscription::cancel. Marks the entry with this id as // cancelled by setting its pointer to null (if the entry was already // removed, nothing matches and nothing happens), then lets sweep decide // whether it is safe to remove it now. void cancel(std::size_t id) noexcept { for (Entry& entry : entries) { if (entry.id == id) { entry.listener = nullptr; } } sweep(); }
// Removes every cancelled entry, but only when no publish is running // (depth == 0). During a notification it does nothing, so the vector // keeps its size and order while a loop is walking it. std::erase_if // (C++20) removes every element the lambda says yes to. void sweep() noexcept { if (depth == 0) { std::erase_if(entries, [](const Entry& entry) { return entry.listener == nullptr; }); } }};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// std::make_shared creates the empty list and the shared_ptr that owns it,// so listeners_ is never null from the start.PriceFeed::PriceFeed() : listeners_{std::make_shared<ListenerList>()} {}
// Gives the listener a fresh id, stores its address at the end of the// list, and returns a handle for that id. `next_id++` uses the current// value, then adds one for next time. Passing listeners_ (a shared_ptr) to// the Subscription's weak_ptr parameter makes a weak_ptr to the same list,// without adding an owner. If push_back has to grow the vector, it moves// the entries to new memory; that is why publish reads entries by index.Subscription PriceFeed::subscribe(PriceListener& listener) { const std::size_t id = listeners_->next_id++; listeners_->entries.push_back({id, &listener}); return Subscription{listeners_, id};}
namespace {// Counts one running notification, and sweeps when the last one ends,// even if a listener throws. An RAII guard: the constructor raises depth,// and the destructor lowers it again. A destructor runs however the scope// is left, by a normal return or by an exception passing through, so depth// can never be left too high. Not copyable: one guard, one count.class Round final {public: explicit Round(ListenerList& list) : list_{list} { ++list_.depth; } // sweep removes cancelled entries only when depth is back to 0, that is // when the outermost publish is ending; an inner round leaves them. ~Round() { --list_.depth; list_.sweep(); } Round(const Round&) = delete; Round& operator=(const Round&) = delete;private: ListenerList& list_;};} // namespace
// One round of notification. A listener's on_price may cancel any// subscription, subscribe, publish again, or throw; the guard and the// loop below are written so that each of those is safe.void PriceFeed::publish(const PriceUpdate& update) { // A reference to the list itself (the object, not the pointer), to // keep the lines below short. ListenerList& list = *listeners_; // From here to the end of the function, depth is one higher, so no // cancel can remove entries while the loop runs. const Round round{list}; // Listeners added during this round wait for the next update. // (Nothing is removed during a round, so the first `count` entries keep // their indexes, and index i is always inside the vector.) const std::size_t count = list.entries.size(); for (std::size_t i = 0; i < count; ++i) { // Read the entry again each time: a listener may have cancelled it, // and a subscribe may have moved the vector's storage. // `if (T* p = ...)` declares p and tests it in one go: the body runs // only if the pointer is not null, that is, not cancelled. if (PriceListener* listener = list.entries[i].listener) { listener->on_price(update); // virtual call: the real listener's code } }} // `round` is destroyed here: depth goes down, and sweep may run
// Counts the entries that are not cancelled. During a round the vector may// still hold marked entries, so entries.size() would be wrong. count_if// returns a signed number, so static_cast turns it into std::size_t.std::size_t PriceFeed::listener_count() const { return static_cast<std::size_t>(std::count_if( listeners_->entries.begin(), listeners_->entries.end(), [](const ListenerList::Entry& entry) { return entry.listener != nullptr; }));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Move constructor: the new handle takes over other's place. other.list_// is moved from and then reset() to make sure it is empty, so when other// is destroyed, its cancel finds no list and does nothing. Only one handle// ever cancels a place.Subscription::Subscription(Subscription&& other) noexcept : list_{std::move(other.list_)}, id_{other.id_} { other.list_.reset();}
// Move assignment, as in `kept = std::move(first);`. This handle may// already hold a place of its own, so it cancels that one first, then// takes over other's place and empties other. The `this != &other` test// makes `x = std::move(x)` do nothing, instead of cancelling x's own place.Subscription& Subscription::operator=(Subscription&& other) noexcept { if (this != &other) { cancel(); // give up what this handle held before list_ = std::move(other.list_); id_ = other.id_; other.list_.reset(); } return *this;}
// lock() turns the weak_ptr into a shared_ptr: the list if it still// exists, or null if the feed (and so the list) is gone or this handle is// empty. Only a live list is told to mark the entry. Either way, list_ is// reset afterwards, so a second cancel (or the destructor's) does nothing.void Subscription::cancel() noexcept { if (const std::shared_ptr<ListenerList> list = list_.lock()) { list->cancel(id_); } list_.reset(); // the feed is gone, or this handle is done}How this code works: PriceFeed::publish and the Round guard
- Raise the count.
const Round round{list}adds one tolist.depth. For a call frommain, depth goes from 0 to 1. While depth is above 0,sweepremoves nothing, so no entry can leave the vector while the loop below is walking it. - Fix the length of the round.
countis the number of entries right now. Entries thatsubscribeadds during the round go after positioncount - 1, so this loop never reaches them. - Visit each position. For
ifrom 0 tocount - 1, the loop readslist.entries[i].listeneragain (never a saved reference or iterator), skips it if it is null (cancelled), and otherwise callson_price. - What a listener may do during its call.
- Cancel any subscription:
ListenerList::cancelsets that entry’s pointer to null, and itssweepdoes nothing because depth is not 0. A later position that is cancelled is skipped by step 3. - Subscribe:
push_backadds at the end, and may move the whole vector to new memory. Reading by index in step 3 is still correct. - Publish again: a second
Roundraises depth to 2, the inner loop runs, and its guard lowers depth back to 1 without removing anything. - Throw: the exception leaves the loop and
publish, and the guard’s destructor still runs on the way out.
- Cancel any subscription:
- Lower the count. When
publishends, normally or by an exception,roundis destroyed: depth goes back down, and if it is now 0,sweepremoves every null entry.
A trace of the test
a_nested_round_does_not_remove_entries_under_the_outer_one, where
first cancels itself and publishes BOLT from inside the ACME round.
Entries are written as id and listener; “x” marks a cancelled entry.
| Step | What runs | depth | Entries | Heard so far |
|---|---|---|---|---|
| 1 | outer publish(ACME) starts, count is 3 |
1 | 1 first, 2 second, 3 third | (nothing) |
| 2 | i = 0: first hears ACME |
1 | same | first:ACME |
| 3 | first calls a.cancel(): entry 1 marked, not removed |
1 | 1 x, 2 second, 3 third | first:ACME |
| 4 | inner publish(BOLT), count is 3; entry 1 skipped |
2 | same | first:ACME second:BOLT third:BOLT |
| 5 | inner round ends; depth is 1, so sweep removes nothing |
1 | same | same |
| 6 | outer loop goes on: i = 1 second, i = 2 third |
1 | same | first:ACME second:BOLT third:BOLT second:ACME third:ACME |
| 7 | outer round ends; depth is 0, so sweep removes entry 1 |
0 | 2 second, 3 third | same |
If step 5 had removed entry 1, second and third would have moved
down to positions 0 and 1. The outer loop’s next position, i = 1,
would then have been third, so second would have missed ACME, and
i = 2 would have read past the end of the vector.
How this code works: Subscription: one owner for each place
A Subscription holds two things: a std::weak_ptr to the feed’s list,
and the id of its entry. Every member function keeps one rule: at
most one handle refers to each entry, and an empty handle does nothing.
-
Making one.
subscribereturnsSubscription{listeners_, id}. Thestd::shared_ptris turned into astd::weak_ptr, so the handle watches the list without becoming one of its owners. -
Moving one.
Subscription b = std::move(a);takesa’s weak pointer and id, then callsreset()ona’s weak pointer. Nowais empty:a.active()is false, and whenais destroyed, itscancelfinds nothing to do. Move assignment (b = std::move(a);) does the same, but first cancels whateverbheld before, so that old entry is not left behind with no handle. -
Cancelling one.
cancelcallslist_.lock(), which gives astd::shared_ptrto the list, or null. There are three cases:- The handle is live and the feed exists: the list is told to mark the entry.
- The feed has been destroyed: its
std::shared_ptrwas the only owner, so the list was destroyed with it, andlock()gives null. - The handle is empty (moved from, or already cancelled):
lock()gives null.
In every case,
list_.reset()then empties the handle, so the destructor’s owncancel(or a second explicit one) does nothing. -
Destroying one. The destructor just calls
cancel. That is what makes the leaving automatic: a handle that goes out of scope, on any path, unsubscribes.
This answers the second question with four rules. Each rule’s behaviour is tested; when marked entries are removed cannot be seen from outside, so the nested-round test is built so that removing them too early would change what is heard:
- Cancelling during a round only marks the entry. The listener is not called again, even later in the same round, but the vector does not change while the loop walks it. Marked entries are removed when the outermost round ends.
- A listener added during a round waits for the next update. The
loop counts the entries before it starts, and reads
list.entries[i]afresh each time, becausepush_backmay have moved the vector’s storage. A range-foror a saved reference would be the same kind of bug as the second flawed example, caused by reallocation instead oferase. - Publishing from inside a listener is allowed.
depthcounts the rounds that are running, so the inner round does not remove entries under the outer one. - A listener that throws ends the round. The exception reaches the
caller of
publish, later listeners are not told about that update, and theRoundguard still lowersdepthand removes marked entries, so the feed keeps working.
The listeners
Section titled “The listeners”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three concrete listeners. Each derives from PriceListener and writes its// own on_price; the feed calls them all through that one function name.// Like every PriceListener, they cannot be copied or moved.
// Shows the latest price of every symbol it has heard about.class PriceBoard final : public PriceListener {public: // `override` asks the compiler to check that this really replaces the // virtual on_price. latest_[symbol] adds the symbol if it is new, then // the new price overwrites the old one. std::map keeps symbols sorted. void on_price(const PriceUpdate& update) override { latest_[update.symbol] = update.cents; } std::string line() const; // "ACME 98.00 | BOLT 21.00"private: std::map<std::string, int> latest_;};
// Keeps every update it hears, as text.class TradeLog final : public PriceListener {public: void on_price(const PriceUpdate& update) override; const std::vector<std::string>& lines() const { return lines_; }private: std::vector<std::string> lines_;};
// Fires once, when one symbol falls below a price, then unsubscribes// itself. It owns its subscription, so destroying the alert also// unsubscribes it.class DropAlert final : public PriceListener {public: // Subscribes itself to `feed` while being constructed. DropAlert(PriceFeed& feed, std::string symbol, int below_cents); void on_price(const PriceUpdate& update) override; // Empty (std::nullopt) until the alert fires; then the message text. const std::optional<std::string>& message() const { return message_; } // True until it fires (or the feed is gone): asks its own handle. bool watching() const { return subscription_.active(); }private: std::string symbol_; int below_cents_; std::optional<std::string> message_; // Members are built in the order they are declared and destroyed in // the reverse order. So the subscription is made after the data that // on_price reads, and is cancelled before that data is destroyed. Subscription subscription_; // declared last, so destroyed first};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The alert subscribes itself: `*this` is the alert being built, passed as// the PriceListener& that subscribe wants, and the returned handle// initializes subscription_ directly. This is safe even though the// constructor has not finished, because subscribe only stores the address;// the feed calls on_price only from a later publish. `symbol` is taken by// value, so it is the alert's own string; std::move hands it to the member// instead of copying it again.DropAlert::DropAlert(PriceFeed& feed, std::string symbol, int below_cents) : symbol_{std::move(symbol)}, below_cents_{below_cents}, subscription_{feed.subscribe(*this)} {}
// Ignores other symbols and prices at or above the limit (an early// return). Otherwise it records the message once and unsubscribes, so it// is never called again and needs no "already fired" flag.void DropAlert::on_price(const PriceUpdate& update) { if (update.symbol != symbol_ || update.cents >= below_cents_) { return; } message_ = symbol_ + " fell below " + money(below_cents_) + ": " + money(update.cents); // This runs inside the feed's publish loop. cancel only marks the // alert's entry (null pointer); the entry is removed after the round. subscription_.cancel(); // during a notification: the feed must allow it}DropAlert owns its subscription, so the “listener outlives its
subscription” rule holds by construction. subscription_ is declared
last, so it is initialized last (after the data that on_price
reads) and destroyed first (before that data). Subscribing *this in
the constructor is safe because nothing calls on_price until the
next publish, which cannot happen before the constructor finishes.
When the alert fires, it calls subscription_.cancel() from inside
on_price, which is the case the naive feed got wrong. Here it only
marks the entry.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
| The listener list | the PriceFeed, through std::shared_ptr |
as long as the feed |
| A listener | whoever created it (main, a window) |
its owner decides; it must outlive its subscription |
| A subscription | whoever subscribed: main, or the listener itself |
the handle lives until destroyed; its entry is marked at cancel or destruction and removed then, or when the current outermost round ends |
| The list, seen from a handle | nobody: a std::weak_ptr |
the handle checks on every cancel |
| A listener, seen from the list | nobody: a raw pointer | valid because the subscription removes it first |
The raw pointer in the list is safe only because of the rule in the
last row, and the rule is kept by the type system as far as it can be:
the only way into the list is subscribe, and it returns a handle that
cannot be copied, cannot be silently dropped, and ends the entry when
it dies. What the type system cannot check is that the listener
outlives its handle; that is why the comment says so, and why the
listener holding its own handle is the safest arrangement.
One case remains forbidden: destroying the feed from inside one of
its own listeners. publish is still running on the feed’s list when
the listener returns. If publish took a local std::shared_ptr copy
of listeners_, the list would at least stay alive, but the loop would
then be running for a feed that no longer exists, and every rule above
would need a second look. The design does not try to support it.
One update, step by step
Section titled “One update, step by step”Text description of the diagram
Main calls publish on the PriceFeed with ACME at 99.50. The feed’s Round guard sets the list’s depth to 1, and the feed counts 3 entries. It calls on_price on the PriceBoard, then the TradeLog, then the DropAlert. The DropAlert sees the price is below 100.00 and sets its message, then calls cancel on its own Subscription. The Subscription calls cancel on the feed’s ListenerList, which marks the alert’s entry; because depth is 1, it is not removed yet. The round ends: the feed’s guard sets the list’s depth back to 0 and the marked entries are removed. Then publish returns to main.
Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant F as PriceFeed
participant B as PriceBoard
participant L as TradeLog
participant A as DropAlert
participant S as alert's Subscription
participant LL as feed's ListenerList
M->>F: publish(ACME 99.50)
F->>LL: Round guard sets depth = 1, count = 3 entries
F->>B: on_price
F->>L: on_price
F->>A: on_price
A->>A: below 100.00: set message
A->>S: cancel()
S->>LL: cancel: mark the alert's entry (depth is 1, so not removed)
F->>LL: round ends: depth = 0, remove marked entries
F-->>M: returnsVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The feed is declared first, so it is destroyed last, after every// listener and handle below.PriceFeed feed;PriceBoard board;// Each subscription is declared after its listener, so it is destroyed first.const Subscription board_subscription = feed.subscribe(board);TradeLog log;// Not const: it is cancelled by hand further down.Subscription log_subscription = feed.subscribe(log);// The alert holds its own subscription. 10'000 is 10000 cents (100.00):// the ' is only a digit separator, for reading.DropAlert alert{feed, "ACME", 10'000};std::cout << "listeners: " << feed.listener_count() << '\n';
// {"ACME", 10'150} builds a PriceUpdate in place: symbol, then cents.feed.publish({"ACME", 10'150});feed.publish({"BOLT", 2'000});feed.publish({"ACME", 9'950}); // the alert fires and unsubscribesfeed.publish({"ACME", 9'800}); // the alert no longer hears thisstd::cout << "board: " << board.line() << '\n';// value_or gives the optional's text, or "none" if it is empty.std::cout << "alert: " << alert.message().value_or("none") << '\n';std::cout << "alert still watching: " << (alert.watching() ? "yes" : "no") << '\n';std::cout << "listeners: " << feed.listener_count() << '\n';
// A block: everything declared inside is destroyed at its closing brace,// in reverse order, the handle before the log.{ TradeLog short_log; const Subscription short_subscription = feed.subscribe(short_log); feed.publish({"BOLT", 2'100}); std::cout << "short log heard " << short_log.lines().size() << " update\n";} // short_subscription is destroyed before short_log: it unsubscribesstd::cout << "listeners after the block: " << feed.listener_count() << '\n';
log_subscription.cancel();feed.publish({"ACME", 9'900});std::cout << "log heard " << log.lines().size() << " updates:";for (const std::string& line : log.lines()) { std::cout << ' ' << line << ';';}std::cout << "\nboard: " << board.line() << '\n';VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The opposite order: the handle outlives the feed.TradeLog survivor;Subscription outlived; // empty for now{ PriceFeed short_feed; // Move assignment: outlived takes the place from the returned // temporary handle, which is left empty and then destroyed harmlessly. outlived = short_feed.subscribe(survivor); std::cout << "while the feed lives, active: " << (outlived.active() ? "yes" : "no") << '\n';} // the feed and its list are destroyed; the handle only observed them// The handle's weak_ptr has expired, so active() is false.std::cout << "after the feed is gone, active: " << (outlived.active() ? "yes" : "no") << '\n';outlived.cancel(); // safe: nothing to doHow this code works: main, one update at a time
Prices are in cents, so 10’150 is 101.50. The alert watches ACME below 100.00.
| Code | Subscribed before it | Who hears it | What changes |
|---|---|---|---|
three subscribe calls |
(none) | (none) | prints listeners: 3 |
publish({"ACME", 10'150}) |
board, log, alert | board, log, alert | 101.50 is not below 100.00, so the alert does nothing |
publish({"BOLT", 2'000}) |
board, log, alert | board, log, alert | the alert ignores BOLT |
publish({"ACME", 9'950}) |
board, log, alert | board, log, alert | the alert sets its message and cancels; its entry goes as the round ends |
publish({"ACME", 9'800}) |
board, log | board, log | the board now shows ACME 98.00 |
block: subscribe(short_log), publish({"BOLT", 2'100}) |
board, log, short_log | board, log, short_log | short_log has 1 line; at the closing brace its handle unsubscribes it at once (no round is running) |
log_subscription.cancel() |
board, log | (none) | only the board is left |
publish({"ACME", 9'900}) |
board | board | the board now shows ACME 99.00 and BOLT 21.00; the log stays at 5 lines |
In the second snippet, outlived = short_feed.subscribe(survivor) is a
move assignment from the returned handle. When short_feed is destroyed
at its closing brace, its list goes with it, the handle’s weak pointer
expires, and active() changes from yes to no without the handle being
told anything.
listeners: 3board: ACME 98.00 | BOLT 20.00alert: ACME fell below 100.00: 99.50alert still watching: nolisteners: 2short log heard 1 updatelisteners after the block: 2log heard 5 updates: ACME 101.50; BOLT 20.00; ACME 99.50; ACME 98.00; BOLT 21.00;board: ACME 99.00 | BOLT 21.00while the feed lives, active: yesafter the feed is gone, active: noRead the output against the requirements:
- Three listeners at the start, two after the alert fires: it left
from inside its own
on_price(FR-4), and the board still shows ACME at 98.00, the update after it left (FR-1). - The short-lived log heard the one update published while it was
subscribed, and leaving the block removed it (FR-2, FR-5) without
an explicit
cancelcall: the handle’s destructor made it. - The main log heard five updates and missed the last one, because it was cancelled before it (FR-2).
- A handle that outlives its feed reports itself inactive, and cancelling it is harmless.
The tests cover each rule, including the re-entrant cases:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Helpers used below (defined above this region, in an unnamed namespace):// - Recorder is a test listener. Each on_price adds "name:SYMBOL" to a// shared vector of strings, `heard`, and then runs `action` if one was// set. `action` is a std::function<void()>: any function or lambda that// takes nothing and returns nothing. That lets a test make a listener// cancel, subscribe, publish, or throw in the middle of a notification.// - joined(heard) puts the strings into one, separated by spaces, so a// whole order of calls is checked in one LLD_CHECK_EQ.// LLD_CHECK(condition) fails if the condition is false, and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception.//// static_assert is checked by the compiler, not when the tests run: the// file does not compile if one is false. These four pin down the copy and// move rules: listeners cannot be copied or moved (the feed knows them by// address), and a Subscription cannot be copied but can be moved, without// throwing.static_assert(!std::is_copy_constructible_v<PriceBoard>);static_assert(!std::is_move_constructible_v<PriceBoard>); // known by addressstatic_assert(!std::is_copy_constructible_v<Subscription>);static_assert(std::is_nothrow_move_constructible_v<Subscription>);
// Two listeners, two updates: each update reaches both, in subscription// order, before the next update starts.LLD_TEST(listeners_hear_every_update_in_the_order_they_subscribed) { PriceFeed feed; std::vector<std::string> heard; Recorder first{"first", heard}; Recorder second{"second", heard}; const Subscription a = feed.subscribe(first); const Subscription b = feed.subscribe(second); feed.publish({"ACME", 100}); feed.publish({"BOLT", 200}); LLD_CHECK_EQ(joined(heard), std::string{"first:ACME second:ACME first:BOLT second:BOLT"});}
// The handle lives only inside the inner block. The first update is heard;// after the block's closing brace the handle's destructor has unsubscribed,// so the second update is not heard and no listener is left.LLD_TEST(destroying_a_subscription_unsubscribes) { PriceFeed feed; std::vector<std::string> heard; Recorder recorder{"r", heard}; { const Subscription subscription = feed.subscribe(recorder); feed.publish({"ACME", 100}); } feed.publish({"ACME", 101}); LLD_CHECK_EQ(heard.size(), std::size_t{1}); LLD_CHECK_EQ(feed.listener_count(), std::size_t{0});}
// FR-4. The list is [before, alert, after]. The alert fires on 99.50 and// cancels itself in the middle of the round; `after` is still told, so the// loop was not disturbed. A second drop (90.00) does not reach the alert:// its message still names 99.50, and two listeners are left.LLD_TEST(a_listener_can_unsubscribe_itself_during_a_notification) { PriceFeed feed; std::vector<std::string> heard; Recorder before_alert{"before", heard}; const Subscription a = feed.subscribe(before_alert); DropAlert alert{feed, "ACME", 10'000}; Recorder after_alert{"after", heard}; const Subscription c = feed.subscribe(after_alert);
feed.publish({"ACME", 9'950}); // the alert cancels itself in the middle LLD_CHECK(!alert.watching()); LLD_CHECK_EQ(joined(heard), std::string{"before:ACME after:ACME"}); feed.publish({"ACME", 9'000}); LLD_CHECK_EQ(alert.message().value_or(""), std::string{"ACME fell below 100.00: 99.50"}); LLD_CHECK_EQ(feed.listener_count(), std::size_t{2});}
// `first` cancels `second`'s handle while the round is running. The lambda// captures b by reference ([&b]) so it cancels the real handle, not a copy// (a Subscription cannot be copied anyway). Proves: a marked entry is// skipped later in the same round, so `second` hears nothing.LLD_TEST(a_listener_cancelled_during_a_round_is_not_called_later_in_it) { PriceFeed feed; std::vector<std::string> heard; Recorder first{"first", heard}; Recorder second{"second", heard}; const Subscription a = feed.subscribe(first); Subscription b = feed.subscribe(second); first.action = [&b] { b.cancel(); }; feed.publish({"ACME", 100}); LLD_CHECK_EQ(joined(heard), std::string{"first:ACME"});}
// `first` subscribes `late` during the ACME round (only once: the// `if (!added.active())` stops a second subscription on BOLT). [&]// captures everything it uses by reference. Proves: `late` misses ACME,// because publish counted the entries before the loop, and hears BOLT.LLD_TEST(a_listener_added_during_a_round_waits_for_the_next_update) { PriceFeed feed; std::vector<std::string> heard; Recorder first{"first", heard}; Recorder late{"late", heard}; const Subscription a = feed.subscribe(first); Subscription added; first.action = [&] { if (!added.active()) { added = feed.subscribe(late); // may move the vector's storage } }; feed.publish({"ACME", 100}); feed.publish({"BOLT", 200}); LLD_CHECK_EQ(joined(heard), std::string{"first:ACME first:BOLT late:BOLT"});}
// On its first call (heard.size() is 1, its own ACME entry), `converter`// cancels `log` and publishes a second update from inside the first round.// The nested round reaches only `converter` (log is marked). Back in the// outer round, log is skipped too. Proves: nested publish works, and the// cancel made inside it holds in both rounds.LLD_TEST(a_listener_may_publish_during_a_notification) { PriceFeed feed; std::vector<std::string> heard; Recorder converter{"converter", heard}; Recorder log{"log", heard}; const Subscription a = feed.subscribe(converter); Subscription b = feed.subscribe(log); converter.action = [&] { if (heard.size() == 1) { b.cancel(); // cancelled inside the outer round... feed.publish({"ACME-EUR", 90}); // ...and a nested round runs } }; feed.publish({"ACME", 100}); LLD_CHECK_EQ(joined(heard), std::string{"converter:ACME converter:ACME-EUR"}); LLD_CHECK_EQ(feed.listener_count(), std::size_t{1});}
// With [first, second, third], an inner round that removed entries// would shift second and third down under the outer loop.// `first` cancels itself and publishes BOLT from inside the ACME round.// Proves: the inner round leaves the marked entry in place, so the outer// loop still reaches second and third at indexes 1 and 2 (if it had been// removed, the outer loop would skip second and then read past the end);// the entry goes when the outer round ends (count 2).LLD_TEST(a_nested_round_does_not_remove_entries_under_the_outer_one) { PriceFeed feed; std::vector<std::string> heard; Recorder first{"first", heard}; Recorder second{"second", heard}; Recorder third{"third", heard}; Subscription a = feed.subscribe(first); const Subscription b = feed.subscribe(second); const Subscription c = feed.subscribe(third); first.action = [&] { a.cancel(); // marked, not removed: the outer round is running feed.publish({"BOLT", 2000}); // the inner round must not remove it either }; feed.publish({"ACME", 100}); LLD_CHECK_EQ(joined(heard), std::string{"first:ACME second:BOLT third:BOLT second:ACME third:ACME"}); LLD_CHECK_EQ(feed.listener_count(), std::size_t{2});}
// `thrower` cancels itself and then throws. Proves: the exception reaches// the caller of publish; `next` is not told about ACME (the round ended);// the cancel made just before the throw still counts (count 1); and the// next publish works normally. (The Round guard's destructor also ran as// the exception left publish, so depth is back to 0 and the marked entry// was removed, but listener_count would read 1 even if it had not been.)LLD_TEST(a_throwing_listener_ends_the_round_but_not_the_feed) { PriceFeed feed; std::vector<std::string> heard; Recorder thrower{"thrower", heard}; Recorder next{"next", heard}; Subscription a = feed.subscribe(thrower); const Subscription b = feed.subscribe(next); thrower.action = [&a] { a.cancel(); throw std::runtime_error{"listener failed"}; }; LLD_CHECK_THROWS(feed.publish({"ACME", 100}), std::runtime_error); LLD_CHECK_EQ(feed.listener_count(), std::size_t{1}); // the cancel still took effect feed.publish({"BOLT", 200}); LLD_CHECK_EQ(joined(heard), std::string{"thrower:ACME next:BOLT"});}
// Moving a handle leaves the old one inactive and the new one active, and// the move did not unsubscribe (the update is heard). When the feed is// destroyed at the block's end, the kept handle becomes inactive, and// cancelling it then is safe. std::move(first) lets the move assignment// take first's place.LLD_TEST(a_subscription_has_one_owner_and_outlives_the_feed_safely) { std::vector<std::string> heard; Recorder recorder{"r", heard}; Subscription kept; { PriceFeed feed; Subscription first = feed.subscribe(recorder); kept = std::move(first); LLD_CHECK(!first.active()); // NOLINT: checking the moved-from state on purpose LLD_CHECK(kept.active()); feed.publish({"ACME", 100}); } LLD_CHECK(!kept.active()); kept.cancel(); // nothing to do, and no crash LLD_CHECK_EQ(heard.size(), std::size_t{1});}Design choices inside the pattern
Section titled “Design choices inside the pattern”Push or pull. This feed pushes the update: each listener gets the symbol and price. The alternative is to pull: the feed only says “something changed”, and each listener asks the feed for what it needs. Push suits small, self-contained updates like this one. Pull suits a subject with a lot of state, where each listener needs a different part of it; the cost is that listeners then depend on the subject’s whole interface.
An interface or a function. subscribe could take a
std::function<void(const PriceUpdate&)> instead of a PriceListener&,
so a lambda could listen without a class. That is common and fine, and
the lifetime rule does not go away: a lambda that captures this or a
reference must not outlive what it captured, so the handle is still
needed, and it is now less obvious who should hold it. Classes make the
“listener owns its subscription” arrangement easy to see.
What the order means. FR-3 promises subscription order, and the tests rely on it. Code that needs a particular order between listeners (the board must update before the chart reads it) is a hint that those two are not independent listeners; call them in order yourself.
When to use it
Section titled “When to use it”Use Observer when:
- one object changes and several others must react;
- the set of reactions is open: it grows over time, or changes while the program runs;
- the object that changes should not depend on the ones that react (a model that must not include its views).
Do not use it when:
- there are one or two listeners, fixed at compile time (call them);
- the reactions must happen in a precise order with results passed between them (that is a sequence of calls, or a pipeline);
- the “listener” really answers a question the subject needs (“may I delete this?”). Observers are told; they are not asked.
- Hidden control flow. Reading
publishno longer tells you what happens. To find out, you must find everysubscribecall. - Lifetime rules. Raw pointers are hidden inside the subject; the subscription handle and the “listener outlives its handle” rule are the price of keeping them safe.
- Re-entrancy rules. Every subject must decide, and test, what happens when a listener cancels, subscribes, publishes, or throws during a round.
- Cascades. A listener that changes another subject can trigger a chain of notifications that is hard to follow, or a loop that never ends if two subjects listen to each other.
Common misuse
Section titled “Common misuse”- Forgetting to unsubscribe. The original Observer bug. In C++, make forgetting impossible with a handle, as here.
- Listeners that depend on each other’s order, or on another listener having already run. Make that dependency an explicit call.
- A global event bus for everything. When every part of the program talks through one bus, nobody can tell who reacts to what. Prefer small, specific subjects.
- Huge updates. Pushing an object’s whole state to every listener on every change wastes work. Send what changed, or let listeners pull.
- Threads added later. A single-threaded Observer that starts being called from two threads breaks in the ways the advanced callout describes.
When the requirements change
Section titled “When the requirements change”| New requirement | What changes |
|---|---|
| Listen to one symbol only | the listener filters (as DropAlert does), or subscribe takes a symbol and the feed keeps a list per symbol |
| Updates arrive on a network thread | hand each update to the main thread through a queue, and publish there; the feed stays single-threaded |
| A listener must not slow the others down | that listener queues the update for later (a Command) instead of doing the work in on_price |
| Some listeners must run before others | a priority in subscribe, kept sorted; consider whether those listeners should be one object |
| A listener wants to stop the rest of the round | a return value from on_price; think twice, since it makes listeners depend on each other |
Exercise
Section titled “Exercise”Exercise: Fix unsubscribe during a notification, three ways
Go back to the NaiveFeed in the second flawed example, where once
detaches itself during publish and the program printed b heard BOLT
twice.
- Explain, step by step through the vector’s contents, why
awas skipped andbwas called twice. - The smallest fix is to loop over a copy of the vector in
publish. Write it. Which bug does it fix, and which bug does it leave? Hint: think of a listener that, during the round, detaches and destroys another listener later in the list. - How does the example’s
PriceFeedhandle both cases? - When is the copy good enough?
Show the explained answer
1. Before the round, the vector is [once, a, b], and the range-for
has saved its begin and end. The loop calls once, which erases itself:
the vector becomes [a, b], with a moved into slot 0, where once
was. The loop moves on to slot 1 and calls b. It then moves on to
slot 2, which is past the new end but not yet at the saved end; that
slot still holds the old copy of b, so b is called again. Then the
loop reaches the saved end and stops. a, in slot 0, was never called.
All of this is undefined behaviour, because erase invalidated the
iterators the loop was using; what we observed is only what these two
compilers happened to do.
2.
// NaiveFeed::publish, changed to loop over a snapshot of the list.void publish(const PriceUpdate& update) { // Copies the vector of pointers (not the listeners) at the start of the // round. A detach during the loop erases from listeners_, not from this. const std::vector<PriceListener*> round = listeners_; // a copy for (PriceListener* listener : round) { // Still a raw pointer from the start of the round: if this listener // was destroyed earlier in the round, the call dangles. listener->on_price(update); }}With this change, the run prints a heard BOLT and b heard BOLT,
once each: erasing from listeners_ no longer affects the loop. But
the copy still holds every pointer from the start of the round. If one
listener detaches and destroys another one that comes later in the
list, the copy calls the destroyed one. We built that case too, and
AddressSanitizer reported a heap-use-after-free inside publish. The
copy also allocates on every publish.
3. It never removes entries during a round. A cancel only sets the
entry’s pointer to null, and the loop reads the entry afresh before
each call, so a listener cancelled earlier in the round, by itself or
by anyone else, is skipped. As long as the rule “the listener outlives
its subscription” is kept, a Subscription is always cancelled before
its listener is destroyed, so a destroyed listener’s entry is
always already null. The vector is cleaned up when the outermost round
ends.
4. When no listener can be destroyed during a round, and it does not matter that a listener detached earlier in the round is still called from the copy (which breaks the first rule above), the copy is simple and good enough, as long as the extra allocation per update does not matter. It is the right first fix for a small program; the marking design is for code where listeners come and go during notifications, as windows and one-shot alerts do.
Related patterns
Section titled “Related patterns”- Mediator: also removes direct links between objects, but a mediator knows the participants and coordinates them, while a subject only broadcasts to whoever subscribed. See Mediator; the two are compared on the Observer vs Mediator page.
- Command: an update can be turned into a command and queued, so a slow listener, or one on another thread, handles it later. See Command.
- State: a subject with a lifecycle often notifies listeners when it changes stage. See State.
Summary
Section titled “Summary”- Observer lets a changing set of listeners subscribe to an object that changes, through one small interface, so the object never names who listens.
- The subscription is a relationship with a lifetime. In C++, give
it an RAII handle that unsubscribes when destroyed, is move-only, and
watches the subject’s list through a
std::weak_ptr, so either side may go first. - A listener is known by its address: make listeners non-copyable and non-movable, and let a listener own its own subscription when it can, declared last.
- Decide what may happen during a notification, and test it: here, cancelling only marks, new listeners wait for the next update, nested publishing works, and a throwing listener ends the round safely.
- Raw-pointer observers fail silently: a destroyed listener is called anyway, and erasing during the loop skips one listener and calls another twice, with no crash.
- Prefer direct calls while the listeners are few and fixed, and do not add threads to an Observer without redesigning its ownership.