Need remove listener?


#1

I have created a custom component. This components has several listeners. For example a Button::Listener. I add those listeners in the constructor. Something like this
 

MyComp::MyComp()
{
    ...
    myButton.addListener(this);
    ...
}

The question is: Do I need to manually remove those listeners in the destructor? Or are they automatically getting removed, when the component is destructed? The myButton is part of the custom component. So its liftime is the same as the component.

I guess, I only need to remove those listeners manually, which refer to objects, that have a lifetime outside my custom component. Correct?


#2

Safe, certainly for buttons and I think for most of the other components, assuming everything is happening on the same thread.   Your object remains valid until after the button has been destroyed.  

(Even if you try something crazy like: 

button.triggerClick()

delete button;

It doesn't break.  In this case you won't get a call back (there's something asynchronous going involving postCommandMessage()) but it won't crash.)

 


#3

Except in that specific example you'll get a double delete.

However, you point about saying it's safe to omit the remove listener call is generally true, yes :) The best way to reason about it is to think about the lifetime of objects; if you're listening to something that has a lifetime that's not tied to your own then you should explicitly remove it in the destructor.


#4

Thanks for the answers. :-)


#5

It's not exceptionally obvious though.  It'd be good to mention it in the documentation as a guarantee.   There are various places where all kinds of magic is invoked to allow a safe asynchronous callback.