It is safe to assign one TArray already to another?

Hi there,

I am just learning the basics of the engine and I have stumbled across this doubt. Let’s say I have one TArray of strings:

TArray<FString> Words = {TEXT("Hello"),TEXT("Friend"),TEXT("Bye")};

And later in my game I decide to assign different values to that same TArray:

TArray<FString> OtherWords  =  {TEXT("other"),TEXT("words")};
Words  =  OtherWords;

Is it safe to do this? It looks weird to me because there isn’t a garbage collector to free the memory allocated by the first words, but I may be missing something about TArray or FString.

Thanks a lot.

Looking at the documentation, yes, you can do that. Words would become a separate complete copy of OtherWords. You could them modify them separately.

TArray: Arrays in Unreal Engine | Unreal Engine Documentation

1 Like

TArray is an analog of std::vector, you can generally be sure it won’t leak memory. E.g. a local TArray (like OtherWords) will allocate some memory when it’s constructed, then automatically free that memory when it goes out of scope (when it’s destructed). When you assign OtherWords to Words, Words’ original allocation is freed and any items it contains are destructed. Words then makes an allocation of the correct size to fit OtherWords’ data, and copies over that data. Finally, when OtherWords goes out of scope, it is destructed and its data is freed.

If you’re 100% certain you don’t want to use OtherWords in any way after assigning it to Words like this, you can do:

Words = MoveTemp(OtherWords);

Which will instead give Words ownership of OtherWords’ internal memory, without actually copying the data. This is slightly more performant. OtherWords will then be left empty.

3 Likes