Sashka
(Sashka)
September 23, 2015, 11:40am
1
I have MyComponent
, which is publicly inherits from UActorComponent
.
MyComponent
has property:
UPROPERTY(BlueprintReadOnly, ReplicatedUsing = OnRep_Slots, Category = Stuff)
TArray<FSlotStruct> Slots;
I clears Slots
:
Slots.SetNum(0);
Then I call
MyComponentInstance.Slots.Reserve(SlotsCount);
Then I adds elements to Slots
in loop by calling:
Slots.Add(NewSlot);
And I encountered, that at some point of adding new elements an reallocating of TArray hapens. Number of added elements is equal to SlotsCount
, used as argument in Reserve
call.
Finaly, to avoid this trouble, I was forced to init cleared TArray with necessary number of default constructed elements, and then rewrite them.
But I want to figure out, what could be the cause of reallocating after reserving.
Please, help me to find th answer.
In such cases it is good to research source code to see when and what it does
Add calls Emplace
https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Containers/Array.h#L1806
Emplace calls AddUninitiazed to create space:
https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Containers/Array.h#L1749
AddUninitiazed reallocates when NumArray (array size varable) with number of added elements is bigger then MaxArray
https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Containers/Array.h#L1302
And MaxArray is set on Reserve
https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Containers/Array.h#L1897
So it should run you predicted, i’m not sure what MoveTemp does but if has to do with anything then use Emplace directly instead of Add.
Also check if you count index right, remeber that size (Num) will be 1 higher them maximum index.
Also note that Reserve argument expects size of entire array, not extra size you want to reserve