Daily Unreal Column #50 - Capture weak object pointer in lambdas
Using lambdas to handle delegates in Unreal can be dangerous due to different objects lifetimes. These issues can be avoided by using weak pointers.
Let’s say you would like to handle an arbitrary event with a lambda defined as following:
auto Func = [this](){ CallingFunctionOnThis(); }
Now, what happens is this is destroyed but the lambda is not removed from the delegate? Most likely thing to happen is that the game will crash.
Here is a safe way to do it using MakeWeakObjectPtr
function:
auto Func = [WeakThis = MakeWeakObjectPtr(this)]()
{
if (WeakThis.IsValid)
{
WeakThis->CallingFunctionOnThis();
}
};