Clarification about IsValid() and nullptr safety

ZackAkai
Wed, 01 Feb 2023 02:14:33 +0000
C++

I was hoping to get a little clarification about best practices regarding safety checks for nullptrs. This is a function which returns the current game session:

if(IsValid(GetWorld()) && (IsValid(GetWorld()->GetAuthGameMode())))
{
	return Cast<AE6KGameSession>(GetWorld()->GetAuthGameMode()->GameSession);
}

return nullptr;

My question is, is the first IsValid(GetWorld()) statement necessary for nullptr safety, or will the following (IsValid(GetWorld()->GetAuthGameMode()) statement automatically check for the world before attempting to access the game mode through the world? In other words, in the event that GetWorld() returned a nullptr, would the program throw an exception on the second statement if the first statement wasn’t there?

*(And yes, I realize this specific example is largely redundant in practice, but I wanted to get clarification on this for cases when it might be more important!)

**(I’m also aware that creating an object of the type to be returned and accessing the next function from that object can also be considered a better practice here, but that can rapidly get verbose in many cases.)

3 posts - 3 participants