How do I avoid memory leaks in C + +

What @Tuerer said is correct! Anything that derives from UObject will be automatically garbage collected when it is no longer hard referenced. Making pointers UPROPERTYs is not necessary. That basically wraps the pointer in a TSharedPtr.

If you’re not familiar with smart pointers, a TSharedPtr is a construct that keeps track of how many references from other smart pointers are pointing at a specific address. When the last smart pointer releases an object, that object is automatically destroyed.

This is by no means comprehensive, but in summation you don’t have to worry too much about memory management. Try not to use structs too often in C++ since they’re not UObjects. Derive from UObject when you can. If you have a reference to a UObject as a class member, make it UPROPERTY or TSharedPtr/TSharedRef to ensure it doesn’t get garbage collected.

That isn’t to say you should never use structs. They’re lighter for memory than classes, especially those derived from UObjects, but you’ll need to be careful with them. Try to only use structs when A) they’re declared inside a function, so they’ll be destroyed when the function completes or B) they’re a member of a class that will be garbage collected, like a UObject.

UPROPERTY ptrs don’t have to be reset manually, but it is good practice to set a raw ptr marked as UPROPERTY to nullptr in the class destructor if it’s still valid at that time. Marking something as UPROPERTY also exposes the property to the reflection system, so that does increase memory load somewhat. As ptrs, they can only be used with objects that derive from UObject.

TSharedPtr/TSharedRef members should definitely be reset in the destructor however or you could be left with dangling pointers. But they do not expose the property to reflection, saving you some memory. They can wrap structs and other objects not derived from UObject.


Runtime DataTable : Import and export game data to and from CSV or Google Sheets while your game is running!

easyCSV : Read data from any CSV and put them in an easy-to-access string map!

iTween : Free, smooth, procedural object animation

3 Likes