I have the following function:
void AddActor(AActor* Actor)
{
if (!IsValid(Actor)) { return; }
if (Actor->IsA(ACertainActor::StaticClass()))
{
//...
}
}
It gets passed some valid and some invalid Actor
-pointers (Actors
that are pending destroy or are already destroyed).
And according to the code documentation IsValid()
returns true
if the object is usable:
/**
* Test validity of object
*
* @param Test The object to test
* @return Return true if the object is usable: non-null and not pending kill
*/
But it crashes at if (Actor->IsA(ACertainActor::StaticClass()))
throwing an access violation:
Exception thrown at 0x00007FF868B56895 (UE4Editor-CoreUObject.dll) in UE4Editor.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
I would expect that IsValid(Object)
checks whether Object
is nullptr
, the engine knows Object
and if it does checks whether is it pending destroy.
So after IsValid(Object)
returned true, Object
should be usable.
Is that not how it works?
Is there any other way to check whether a pointer points to a valid object that can be used?
Well, from your exception:
Exception thrown at 0x00007FF868B56895 (UE4Editor-CoreUObject.dll) in UE4Editor.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
in clearly states that this pointer is not nullptr, it is of value 0xFFFFFFFFFFFFFFFF
. So IsValid
works as written in docs:
Return true if the object is usable: non-null and not pending kill
You should initialize your pointer to nullptr
.