Raw Pointer vs Smart Pointer

I was wandering why all the code of the game framework favors raw pointers over smart pointers, because thats not the case with the editor code.
Whats the reasoning behind that decision?

That’s because UE4 does reference counting and garbage collection for UObject derived classes (as long as they are stored in UPROPERTY tagged properties). This is why you use NewObject<> to instantiate UObject derived classes and don’t have to delete them manually. Smart pointer templates are used for non-UObject classes, which are used generally outside the gameplay framework and for data that doesn’t interact with the framework directly.

The “raw pointers” under a UPROPERTY macro within UObject class are not “raw” at all. When you attach a UPROPERTY to those “raw pointers”, UE4 automagically makes them “strong” references, which are basically the same as smart pointers.

Yep, UBT / UHT does actually convert a lot of Raw pointers to smart ones when you compile. Take a look at the generated headers, they’re often quite different.

After thinking about it a little bit its clear to me now. The UProperty “pointer” facilitates not only memory management but also saving, replication ect. In contrast smart pointer only manage the lifetime of an object.
In the end my question was stupid, sorry about that

Your question wasn’t stupid at all, the automatic UObject lifetime management isn’t obvious at first sight when you dive directly into the source without prior explanation.

1 Like