RealDocs

TArray::SetNum

function Core Since 4.0
#include "Containers/Array.h"
Access: public

Description

Resizes the array to exactly NewNum elements, default-constructing any new elements if growing, and destructing trailing elements if shrinking. Analogous to std::vector::resize.

Caveats & Gotchas

  • When growing, new elements are default-constructed — not zeroed. For POD types with no default constructor the new elements contain garbage. Use SetNumZeroed() if you need zero-initialized new slots.
  • When shrinking, SetNum calls RemoveAt internally which may trigger a reallocation depending on EAllowShrinking. Pass EAllowShrinking::No in tight loops to avoid repeated shrink-reallocations.
  • The bool bAllowShrinking overload is deprecated in UE 5.6 — use EAllowShrinking::No or EAllowShrinking::Yes.
  • SetNum(0) is a valid but unusual call — use Reset() or Empty() instead, as those better express intent and avoid the overhead of the size comparison.

Signature

void SetNum(SizeType NewNum, EAllowShrinking AllowShrinking = UE::Core::Private::AllowShrinkingByDefault<AllocatorType>())

Parameters

Name Type Description Default
NewNum SizeType The desired number of elements after the call.
AllowShrinking EAllowShrinking Controls whether memory is released when reducing the count. UE::Core::Private::AllowShrinkingByDefault<AllocatorType>()

Return Type

void

Example

Pre-size an array for direct index assignment C++
TArray<FVector> Positions;
Positions.SetNum(64); // 64 default-constructed FVectors

for (int32 i = 0; i < 64; ++i)
{
    Positions[i] = FVector(i * 100.f, 0.f, 0.f);
}

Version History

Introduced in: 4.0

Version Status Notes
5.6 stable

Feedback

Was this helpful?

Suggest an edit

Select a field above to begin editing.