Why we don't need to protect the pointer inside this loop?

I don’t understand why we don’t need to protect the Actor pointer from being null. Is TArray already dealing with the pointers it stores inside? Elaborate a bit on this if you can or point me in a direction to look for more information.

bool UOpenDoor::IsEnoughMass() const
{
	TArray<AActor*> OverlappingActors;
	if (!PressurePlate)
	{
		UE_LOG(LogTemp, Warning, TEXT("There is no pressure plate, nullptr found instead"));
		return false;
	}
	PressurePlate->GetOverlappingActors(OUT OverlappingActors);
	float MassCount = 0.f;

	for (AActor* Actor: OverlappingActors)
	{
		if (Actor)
		{
		UE_LOG(LogTemp, Warning, TEXT("Overlapping actor: %s"), *Actor->GetName());
		MassCount += Actor->FindComponentByClass<UPrimitiveComponent>()->GetMass();
		}
	}
	
	return MassCount >= MassToOpen; 
}

If(Actor) is dealing with it being null isn’t it? Because otherwise that should return false if I’m reading it right, so effectively you could test this by making nothing in it, and using a log with an else off that right?
Basically it’s looping through the array, but only executing if the actor from the array is valid. Though I’m not entirely sure it would execute with nothing in it anyway, as you’re looping through looking for any of them, the if may purely just be an extra step in case, but I wouldn’t remove it because I’m paranoid, and empty pointers cause crashes.

The

if (Actor)
{

}

is what i used because i am paranoid too.
The thing I am asking is why in the lesson is told that we don’t need to use this if and i don’t understand why.
The following code is what i am refering to:

TArray<AActor*> OverlappingActors;
for (AActor* Actor: OverlappingActors)
{
    //No need to manage null pointers here but i think Actor could be null
}

I’m going to assume if the TArray had nothing then it will have 0 actors and so the for loop wouldn’t go through anything. Just scary to trust but it makes sense. So saying for each nothing do this is probably simplified to do nothing. Next block.

A null actor wouldn’t be in the array.

1 Like

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

Privacy & Terms