In this lesson, you will learn how Unreal Engine’s reflection system enables the Garbage Collector (GC) to automatically track and safely destroy your UObject instances.
The Role of Reflection in Memory Management
In standard C++, if you instantiate an object with new, you are responsible for calling delete to prevent memory leaks. Unreal Engine simplifies this via the Garbage Collector. However, the GC cannot simply scan your entire computer's memory to find your objects. Instead, it relies on the Reflection System to keep a "census" of every UObject currently alive in your game.
For the GC to manage your objects, it must know exactly which pointers reference them. If you create a UObject but don't tell the engine where it is, the GC might assume it’s unused and delete it prematurely, leading to a crash.
Using UPROPERTY for Tracking
The magic happens through the UPROPERTY() macro. When you store a reference to a UObject inside another UObject (or an AActor), you must tag that pointer with UPROPERTY().
UCLASS()
class UMyInventoryManager : public UObject
{
GENERATED_BODY()
public:
// Because this is a UPROPERTY, the GC knows that 'CurrentItem'
// is in use and will not delete it as long as this reference exists.
UPROPERTY()
UItemData* CurrentItem;
};
When the GC runs, it performs a "reachability analysis." It starts from known root objects and traverses every pointer marked with UPROPERTY(). If an object is no longer reachable through these tracked pointers, the engine marks it for collection.
Why this matters
If you store a UObject* in a raw pointer without UPROPERTY(), the GC remains "blind" to that reference. Even if your object is still technically in use, the GC might sweep it away during a cleanup cycle. By consistently using the reflection system to declare your object relationships, you ensure that the engine manages your memory safely, allowing you to focus on gameplay logic rather than manual memory deallocation.
Key Takeaway: To ensure the Garbage Collector keeps your UObjects alive, you must store references to them as UPROPERTY members, allowing the reflection system to track their lifecycle automatically.