What's the difference between using TWeakObjectPtr or using UObject*

Dear ,

#There’s a Huge Difference, One Will Always Crash

There’s a huge game-breaking difference between your two examples!


This will never crash

    TWeakObjectPtr<UObject> WeakPointer;
   if( WeakPointer.IsValid()) {}

The below code is guaranteed to crash every single time based on how you’ve written in it

UObject *Obj;
if(Obj->IsValidLowLevel()){}

reason = you are de-referencing a pointer that is pointing to nothing (dereference is the operator)

#IsValidLowLevel()

IsValidLowLevel is not meant to be used for verifying the pointer, it is for verifying the integrity of the UObject after it is already known to exist, but might have been deleted recently. See below for how you can verify the pointer itself.

#Solution
If using raw c++ pointers, you can just do this

UObject* Obj;
if(Obj != nullptr)
{
  //Safe!
  Obj->GetName();
}

The above using raw C++ pointers, and the example using .IsValid() are the two cases that are equivalent, and both are safe.

#Why is this such a big deal?

Whether you understand this difference properly is what makes your game crash to desktop constantly, or run stable all the time (minus any infinite while loops hee hee) :slight_smile:

3 Likes