Observer
The observer pattern lets many listeners react when a subject changes. In C++ that is a list of callbacks (std::function, a virtual Listener, or a signal library). The hard part is lifetime: a listener must not be called after it dies.
Detailed Explanation
A button fires onClick. A model fires onChanged. The button should not include every dialog that cares. Observers subscribe, get notified, and unsubscribe. The subject stores non-owning handles to the observers.
Three C++ spellings:
- Virtual listener.
struct Listener { virtual void onClick() = 0; };The subject holdsvector<Listener*>. Simple, typed, easy to leak if you forgetunsubscribein the destructor. std::function<void()>list. Lambdas work. Unsubscribing is awkward (you need an id). A lambda that captured[this]dangles if the observer dies first.- Signals/slots (Boost.Signals2, Qt). Connections are objects; destroying the connection unsubscribes. Closest to "safe observer" in large GUIs.
Notification order is usually subscription order. Do not assume it. An observer that mutates the subscriber list while you iterate it invalidates the walk — copy the list before calling, or use indices.
Reentrancy: notify calls obs->onClick() which calls subject.subscribe or unsubscribe. Decide whether that is allowed. Copying the list first makes unsubscribe during notify safe for this round.
Ownership: the subject should not shared_ptr the observers by default; that extends their life in surprising ways. Prefer raw pointers plus explicit unsubscribe, or weak_ptr if observers are already shared_ptr. weak_ptr::lock skips dead observers.
This is not the observer you want for a single "when done" callback; that is a function or a future. Observer is for fan-out.
GUI toolkits already have this. Do not write a third signal library for a two-button app. Write a vector<function<void()>> and document that listeners must outlive the subject or unsubscribe.
Code Examples
#include <algorithm>
#include <iostream>
#include <vector>
struct Listener {
virtual ~Listener() = default;
virtual void onClick() = 0;
};
class Button {
std::vector<Listener*> listeners_;
public:
void subscribe(Listener* l) { listeners_.push_back(l); }
void unsubscribe(Listener* l) {
listeners_.erase(std::remove(listeners_.begin(), listeners_.end(), l),
listeners_.end());
}
void click() {
auto copy = listeners_; // safe if an observer unsubscribes
for (auto* l : copy) l->onClick();
}
};
struct Log : Listener {
void onClick() override { std::cout << "click\n"; }
};
int main() {
Button b;
Log log;
b.subscribe(&log);
b.click(); // prints: click
b.unsubscribe(&log);
}Common Gotchas
Not unsubscribing in the listener destructor
the next `click` is a use-after-free. Unsubscribe, or use `weak_ptr`.
Iterating `listeners_` while it mutates
copy first.
`[this]` lambdas are observers that dangle
store a token and unsubscribe, or do not use a lambda.
`shared_ptr` observers keep objects alive
a dialog that should close will not, if the button still owns it.