Hard
A colleague returned by value
What happens when this program runs?
main.cpp
struct Colleague;
struct Mediator {
virtual void notify(Colleague* sender, const std::string& event) = 0;
virtual ~Mediator() = default;
};
struct Colleague {
Mediator* mediator; // non-owning back-reference, no lifetime guarantee
explicit Colleague(Mediator* m) : mediator(m) {}
void trigger() { mediator->notify(this, "clicked"); }
};
struct ConcreteMediator : Mediator {
void notify(Colleague*, const std::string& event) override {
std::cout << "mediator handling: " << event << "\n";
}
};
Colleague makeColleague() {
ConcreteMediator m; // local mediator
return Colleague(&m); // colleague outlives the mediator it points to
}
int main() {
Colleague c = makeColleague();
c.trigger(); // mediator is long gone
}25 of 44 in Design Patterns