How it works...

This recipe combines both of the previous recipes in this chapter so far. We override EndPlay, which is an event that's implemented as a virtual function, so that we can execute code when our DelegateListener leaves play.

In that overridden implementation, we call the Unbind() method on the delegate, which unlinks the member function from the DelegateListener instance.

Without this being done, the delegate dangles like a pointer, leaving it in an invalid state when the DelegateListener leaves the game. Using BindUObject() helps avoid most of these situations, and just a few unfortunate timing situations could cause calls on objects to be marked for destruction. It is still a good practice to unbind delegates manually, even when using BindUObject(), because when these timing mishaps cause bugs, they're almost impossible to track down.