Should I unbind a lambda declared inside a function?

I have this doubt.

In this case, the lambda is unbinded after being executed?

Because the variable is destroyed when it reaches the end of the function.

Or is a dangling pointer created? (Inaccessible)

void Fuction()
{
AnyLambdaType Delegate;
Delegate.BindLambda( ( ) { } )
ThreadExecuteLambda(Delegate);
}

Or the correct thing is to make the variable global (class member) and always unbind before rebinding

AnyLambdaType Delegate;

void Fuction()
{
Delegate.Unbind();
Delegate.BindLambda( ( ) { })
ThreadExecuteLambda(Delegate);
}

Or does the garbage collector take care of that?

Thank you so much!!

It depends a bit on the implementation of ThreadExecuteLambda. I can’t find a function called that in my 5.2 so that’s either part of your pseudo code or something local.

I would usually expect a function like that to take the delegate and make a copy of it before returning control to Function. If the threading has made a copy it doesn’t matter what happens to the instance in Function.

If ThreadExecuteLambda is taking and keeping a reference to the delegate for the duration of the thread then you do have some potential issues with the thread referencing a variable that has gone out of scope. But in this case the lambda’s never really unbound from the delegate, the delegate just ceases to exist.

No, this is not going to help anything and would probably cause more grief than anything else. Maybe in the second case (where the thread keeps a reference) this solves some problems, but it introduces others because you’ve just rebound the delegate that might be in use by the first call. And now two threads are using the lambda from the second call (which probably isn’t what you want). Plus, unbinding then binding is redundant. You only need to call Unbind if you want it to not be bound to anything.

A delegate is not a UObject, so the garbage collector is irrelevant.

It’s also worth noting that all of this is only relevant for the delegate itself. If you start doing captures of things by pointer or reference you may have issues.

1 Like

Yes, I was speaking in general terms. I did it this way because I’ve seen many different ways Unreal uses to create and execute Delegates/Task/TFunctions/UFuntions/Lambdas…

And I was worried about the case that the pointer to the functor was not deleted from memory. Especially when I know that this function is going to be executed thousands of times.

Thank you very much for your explanation.
It has been very useful for me.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.