C/C++ Arena

Step 3 of 6

Observers with weak_ptr

In the Observer pattern a subject notifies listeners when something happens. The hard part in C++ is lifetime: if a listener is destroyed while the subject still holds a pointer to it, the next notification uses a dangling pointer.

Storing std::weak_ptr solves it. The subject doesn't keep listeners alive, and lock() tells you whether each one still exists:

for (auto& w : listeners_) {
    if (auto l = w.lock()) l->on_event(e);    // still alive: notify
}

Your turn: implement Scoreboard::subscribe and Scoreboard::publish. publish notifies every living listener in subscription order, removes expired ones, and returns how many were notified.

Previous: A factory registry Next: Pimpl