Course contentsShow
← Unreal Engine Game Development
Lesson 167 of 8803. C++ and UObject ArchitectureFree lesson

Managing Object Lifetimes with UPROPERTY References

Understand how marking member pointers with the UPROPERTY macro prevents the garbage collector from destroying objects while they are still in use.

In this lesson, you will learn how the UPROPERTY() macro acts as a vital "anchor" to prevent the Unreal Garbage Collector from prematurely destroying your custom objects.

The Problem: Invisible Destruction

In standard C++, if you create an object with NewObject<T>() and store a pointer to it in a raw member variable, Unreal’s Garbage Collector (GC) has no way of knowing that your class still needs that object. Every so often, the GC performs a "mark-and-sweep" pass. If it determines that an object is not referenced by anything the system recognizes, it will delete the object from memory to save space. When your code later tries to access that pointer, you will encounter a crash because the memory has been wiped.

The Solution: Registering with UPROPERTY

To tell the Garbage Collector, "I am using this object, do not delete it," you must mark your pointer with the UPROPERTY() macro. When you add this macro, the reflection system adds that pointer to a "reference graph." The GC traverses this graph; if it sees your pointer marked as a UPROPERTY, it treats the referenced object as "reachable" and keeps it alive.

Consider this example inside your class header:

UCLASS()
class AMyActor : public AActor
{
    GENERATED_BODY()

public:
    // This object will be kept alive by the Garbage Collector
    UPROPERTY()
    UMyCustomObject* MyManagedObject;

    // WITHOUT UPROPERTY, the GC might destroy this object 
    // even if the pointer still exists in memory!
    UMyCustomObject* MyUnsafeObject;
};

Why it Matters

By using UPROPERTY(), you shift the burden of memory management from yourself to the Unreal Engine. You no longer need to manually delete objects or worry about complex ownership hierarchies. As long as your AMyActor instance exists and contains a UPROPERTY reference to MyManagedObject, that object is guaranteed to persist. Once the AMyActor is destroyed or the reference is set to nullptr, the GC will eventually clean up the object automatically.

Key Takeaway: Marking a pointer with UPROPERTY() registers it with the Garbage Collector, ensuring the referenced object remains in memory as long as the parent class holds that reference.