Medium
Observer holding its Subject through a weak_ptr
What happens when this program runs?
main.cpp
struct Subject : std::enable_shared_from_this<Subject> {
int state = 99;
};
struct Observer {
std::weak_ptr<Subject> subject;
void notify() const {
auto sp = subject.lock();
std::cout << sp->state << "\n";
}
};
int main() {
Observer obs;
{
auto s = std::make_shared<Subject>();
obs.subject = s;
} // s's refcount drops to 0, Subject destroyed
obs.notify();
}6 of 44 in Design Patterns