0

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?

Kadir Erdem Demir
  • 3,531
  • 3
  • 28
  • 39

1 Answers1

1

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; }
} 
Caleth
  • 52,200
  • 2
  • 44
  • 75