Broadcaster deleted before Listener -- How to detect and skip removal of listener

I’m using a TableListBox with a custom row component. Each row component is registered as a TableHeaderComponent::Listener so it gets notified when columns are resized and can change its layout accordingly. I’m doing all of that in what I think is a pretty standard way: each row component adds itself as a listener in its constructor, and removes itself in its destructor.

This works without any issues while my app is running, but whenever I now quit it I get a crash that’s triggered by my row component trying to remove itself as a listener. I’m assuming the issue is that the TableHeaderComponent is already destroyed by the time a row tries to remove itself.

Surely it’s a common scenario that a broadcaster might be deleted before one of its listeners. How do you guys deal with that?

No, that’s not common. Your listeners need to be removed prior to their broadcasters being deleted. In the component that contains the broadcaster, I remove any sub-components that are listeners in the destructor’s [Destructor_pre] section, prior to the broadcaster sub-components being set to nullptr in the main part of the destructor.

I can think of several solutions…

  1. Adjust the lifetime of objects so the broadcaster always outlives it’s listeners

  2. Use Shared/Weak pointers, listeners would generally have weak pointers to the broadcaster.

  3. Don’t call removeListener in the d’tor, instead have a different object that contains both the broadcaster and listener do the adding and removing of listeners.

  4. Add a listener method to indicate that the broadcaster is about to be deleted, then call all the listeners in the broadcasters d’tor so they can remove their reference to the broadcaster.

Normally option 2 would be my preference, as it reduces the number of references to the broadcaster, thus reducing it’s dependency and therefore complexity of the system. However if the lifetime of the broadcaster/listeners isn’t as clear cut then possibly option 3. If for one reason or another option 3 would require a lot of work option 4 could be a temporary work around. I personally steer away from option 1 as someone will come along and change the lifetime order again at some point and you’ll end up with a regression.