Unreal c++ memory safety - dangling pointers

Couldn’t google a definite answer so I hope I’ll get one here.

My question is this. In straight c++ if I had an object of class A that had a member B* that pointed to some object, once that object got deleted by something I was in trouble if I didn’t implement some kind of mechanism that would clear all the pointers to it.

Now I’m wondering how Unreal’s garbage collector, reflection and other custom stuff affect that situation. Will IsValid() check save me, or do I still have to be careful about this?


If the Pointer is a UPROPERTY then the Garbage Collector handles it itself, and doesn’t allow that object to be fully deleted from memory if it’s referenced by something else (I believe). if the pointer isn’t a UPROPERTY then UE’s GC has no idea and you’ll get all the usual quarms with null pointers.

What you probably want is a TWeakObjectPtr - which allows the pointed-to object to be fully deleted and automatically nulls the pointer.

The exception is if the classes to which you point are not in the UObject hierarchy, right, @TheJamsh? Like, if you’re new-ing them manually, I would hope that the GC would leave them alone.

Yeh I believe that’s correct too :slight_smile: