Good practice in UE5 is to make sure you're not calling a function on a nullptr.
One method of doing this would be calling the pointers IsValidLowLevel() function like follows...
if (ActorPtr->IsValidLowLevel())
{
ActorPtr->DoSomething();
}
But why does this actor pointer have guaranteed access to this function if it is indeed a nullptr? Shouldn't the program crash if you call a function on a nullptr the same as if I called the ActorPtr's DoSomething() function? And is there a difference in how these functions are called?
I'm also aware that there are other and probably better ways to nullcheck since it also does a bunch of other checks that might not be necessary, but I'm just curious why you can even do this in the first place.
I've checked out UE5's documentation on this function, but it's super helpful and says that it does a nullcheck and doesn't go into how it does it.
Dereferencing a nullptr
is undefined behavior. A crash is not guaranteed, anything (literally) is allowed to happen and the compiler is not required to warn you about it - it can just assume it never happens (because if it did, that would mean you break the rules and then it's allowed to do whatever). And if the function checks for nullptr
internally, then that is just pointless since this
is not allowed to ever be nullptr
inside a member function, so any sensible optimizing compiler is just going to optimize away any such check.
What you want in your current situation is probably if (ActorPtr && ActorPtr->IsValidLowLevel())
.