Search code examples
c++11observer-pattern

Implementing observer pattern without unsubscribe method


When I implement observer pattern before, I always used to hold a reference to the owner inside of listener. And in listener's ctor I used register and in dtor I used to unregister.

But this time around I don't want to hold a reference for keeping weak coupling between this classes.

I come up with an implementation with weak-ptr. My question is, if it is ok to implement observer pattern without unsubscribe method with weak-ptr? Is there any case that I can get into trouble?


Solution

  • Yes, using a weak_ptr to an observer is a natural fit.

    However, your implementation has a data race where elem expires during your loop, you probably want to instead do

    for (auto elem : listenerList)
    {
        auto locked = elem.lock();
        if (locked) { locked->update(val); }
        else { anyExpired = true; }
    }