Do WeakLambda's need extra steps to unbind?

I have used Lambda’s in C# and JS. I was wondering if I needed to worry about when using them in ue4 C++. (E.g. Removing from memory, crash issues on builds or etc.)

ClassA.cpp
if(Responder)
{
MoveActivity->OnRespondToActivityStart.Clear();

      MoveActivity->OnRespondToActivityStart.AddWeakLambda(this, [=]{
      Responder     
       ->PlaySpeechFromTable("MOVE_TO");
 });
 }

MoveActivity.h
DECLARE_MULTICAST_DELEGATE(FOnRespondToActivityStart);
FOnRespondToActivityStart OnRespondToActivityStart;

1 Like

Bind function returns FDelegateHandle which you can later use to remove bind, on non-dynamic delegate you need to do that even if you bind from function pointer, similar to UE4 timers. You can also remove all binds with specific object scope at once which is probably what you looking for, you can if you delete binded scope object if want to be 100% safe:

With non-multicast delegate since you can have only one bind on those you just clear it.

C++ (UE4 use normal C++) don 't have memory management, pointers (types with * and this is also pointer) are just integers in memory address and they don’t change state when object is pointing to is deleted, creating so called invalid pointer that is hard to validate. UE4 it self has memory management on it’s own but it’s only for UObjects (which all actors are) and it only for variables with UPROPERTY which engine can see in reflection system, engine will null them when object they pointing to get destroyed (not sure if it also checks scope objects in delegates under UPROPERTY). It wont do that with local varables that this technically is so if delegate is executed on dead object you may have crash.

As “Removing from memory” lambda is compiled same as normal function, compiler will place machine code in specific address like any other function and delegate will only reference to it using function pointer like in the case of other functions (it will put const value with address on argument you placeing lambda in). Since entire code is loaded in memory anyway in time of execution you should not be worry about it. Also local valuables in lambda will be deallocated (if they been allocated at all since compiler tend to optimize them away by keeping them in CPU registers when function is executed since allocation is expensive, C++ unlike C# and JS is compiled directly to CPU machine code allowing tho do this kind of things) like in any other function after execution except variables that pointers pointers point too, in that case UObjects you using in function are already managed by UE4 so you also should not be worried about that or else you so some crazy things with non-UObjects.