I have a RandomInt and FString called Text that I want to pass into a AsyncTask problem is if use the variables inside the AsyncTask it returns Chinese and in case of Int it simply returns 1 no matter what the actual int is.
I assume this is due to the [&] capture by reference, It works fine if a capture by value, Which means i am forgetting a operator or writing wrong syntax.
it seems you get Chinese when you try to capture by Reference and use a parameter of the function i.e.
void MyCustomFunc(FString Sentence)
{
// You will get Chinese if you try to log the Sentence that passed as a parameter.
AsyncTask(ENamedThreads::AnyHiPriNormalTask, [&]()
{ GLog->Log(Sentence) });
}
Only Solution I see for now is don’t use the passed parameters inside the anonymous function instead use the normal attributes of your class.
The actual solution would be to capture your function parameter by value instead of by reference. You could do this as either an equivalent capture all [=] or just the specific data you want [ S = Sentence ] (using S in your Log call).
Capturing by reference can be particularly dangerous for any async work unless you have some strong guarantee that the reference will be kept alive by the time the lambda accesses it.
In this case, you’ve captured a reference to stack data which is going to be invalidated as soon as you return from this function. There’s no way to know what might be at that memory address when your lambda runs.
This is just how the FString is interpreting the random data of the reference. It’s probably gibberish and not really Chinese. Anymore than you could interpret a random stream of numbers as a text using the classic ASCII table and it could look like words unless you can actually read in which case it’s just random letters in a random order. You could just as easily get something that looks Greek or Russian.