0

I want to know if the following code would return nullptr reliably without any complications:

TArray<ASomeActor*> SomeActors;

ASomeActor* SomeActor = SomeActors[0];

return SomeActor;
rustyx
  • 80,671
  • 25
  • 200
  • 267
Shiro
  • 2,610
  • 2
  • 20
  • 36

3 Answers3

3

No. According to documentation, that is not allowed:

Passing an invalid index — less than 0 or greater than or equal to Num() — will cause a runtime error.

rustyx
  • 80,671
  • 25
  • 200
  • 267
2

It is not safe to try to access an invalid index of a TArray, but the engine provides a convenient way to check the index before you try to read it:

TArray<ASomeActor*> SomeActors;
if (SomeActors.IsValidIndex(0))
{
    ASomeActor* SomeActor = SomeActors[0];
    return SomeActor;
}
else
{
    return nullptr;
}

Would be safer. It's also perfectly reasonable to check the array's size before trying to read it:

If (SomeActors.Num() > 0)
{
    return SomeActors[0];
}

You can use a ternary operator if you need to make a const assignment:

const ASomeActor* SomeActor = SomeActors.IsValidIndex(0) ? SomeActors[0] : nullptr;
Kevin Mack
  • 1,174
  • 1
  • 9
  • 20
0
TArray<ASomeActor*> SomeActors;
ASomeActor* SomeActor = SomeActors[0];
return SomeActor;

Above code cause run time error because the index is greater than or equal to the size of array.

Before accessing element using index, check the index with size of array. Index should be less than the size of the array.