IsValid() throws nullptr exception

Hey! I’m new to C++ and wondering whether I’m doing something wrong.
I’m checking whether my Character is valid with IsValid(Character) but it throws a “reading access violation: this was nullptr” loosely translated.
Shouldn’t the very purpose of IsValid() be to check for nullptr and not to crash the project if it encounters one?

I ran into the same when I was learning C++ in UE. IsValid() is usually used to test whether the actor is still alive and not pending kill. The actor can be pending kill, meaning that it has been destroyed in the game, but it’s still in memory waiting to be garbage collected.

In that case, the actor is not valid, meaning that calling something on it would result in an error, but is still in memory, so the pointer to it is not null. This case shows that these are two are not same. So in your case, you want to probably really use the null pointer check first: if (Character != nullptr).

In C++ specifically, you can also just write if (Character). Since a pointer is really just an int number, and integers do get converted to booleans implicitly, then if it’s a null pointer, it’s always 0, meaning false, and if it’s in memory, then it’s a non zero pointer address, so it will be true.

1 Like

The issue here is not related to the Character, you called this method on a AProductionFacility* that was nullptr.

3 Likes

thanks for the answer!