Search code examples
c++observer-patternobservable

When and who to detach observers when the observer has longer life span than the observable


I encountered this problem using a third party library provided by a different group in the company (written in C++).

In the destructor of Observer, it detaches itself from all observables it subscribes to, this part makes sense to me. But in the destructor of Observable, it checks if the observable has any observer that's still in it's subscriber list. If so, throws an error.

I am going to put the fact that it intentionally throws an error in the destructor aside. Can someone try to explain to me the why the observable should expect no observers to outlive itself or is this just a bad design. If this is a bad design, when we are in circumstances when the observer outlives the observable, are there good ways to handle it?


Solution

  • If the Observer has a pointer (or reference) to the Observable, and the Observable is destroyed, that pointer will be invalid. The author is just trying to avoid dangling references.

    There are three usual solutions, I think.

    One is to do exactly what this code does, perhaps calling abort() rather than throwing an exception in the destructor.

    Another is to have the Observable's destructor de-register itself from any Observers.

    The last is to use "smart pointers" (e.g., a reference-counted shared_ptr) to guarantee that the Observable outlives any Observer.