Question on return local array

This is my implementation of GetValidWords().

It works fine but I just have a question on why it works. The return statement returns the address of the locally declared array ‘TArray ValidWords’. Surely when the function returns the local variable goes out of scope and the address of the local variable is invalid. Shouldn’t the local variable be made static or new memory allocated for the array to be returned?

Or is a copy of the whole array made and returned?

TArray<FString> UBullCowCartridge::GetValidWords(const TArray<FString>& WordList) const
    TArray<FString> ValidWords;
    for (int32 i = 0; i < WordList.Num(); i++)
        int32 WordLength = WordList[i].Len();
        if (WordLength >= 4 && WordLength <= 8)
            if (IsIsogram(WordList[i]))

    // Debug print statements
    //for (int32 i = 0; i < ValidWords.Num(); i++)
    //    PrintLine(TEXT("%s"), *ValidWords[i]);

    return ValidWords;

It does not. This function returns by value, it is not returning a pointer or reference. When you return by value you implicitly moving the local variable and often times the compiler will do Return Value Optimisation (RVO) where the object being returned is the same object as its destination. i.e. if RVO happens

const TArray<FString> Thing = GetValidWords(Words);

Thing and ValidWords within the function are in fact the same object.

This blog post goes into far more detail:

Yes, after a bit more reading etc. I realised my misunderstanding. Thank you.

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

Privacy & Terms