In this lesson, you will learn how to use the UPROPERTY macro to ensure your object pointers stay valid and safe from being prematurely deleted by Unreal’s Garbage Collector.
The Problem: Dangling Pointers
In standard C++, if you create an object and keep a pointer to it, you are responsible for its memory. In Unreal Engine, the Garbage Collector (GC) periodically scans your objects to see which ones are still in use. If the GC thinks an object is no longer "referenced" by anything, it will destroy that object to free up memory.
If your C++ pointer is just a raw variable (e.g., AActor* MyTarget), the Garbage Collector has no idea that you are still using that object. If the GC deletes the object, your pointer becomes a dangling pointer—it now points to a memory address that contains garbage data. Attempting to access it will cause your game to crash.
The Solution: UPROPERTY()
To tell the Garbage Collector, "Hey, I'm still using this object, don't delete it!" you must mark your pointer with the UPROPERTY() macro.
When you add UPROPERTY() above a pointer, Unreal’s reflection system takes note of it. The GC will see this reference and increment the object’s "reference count," ensuring the object stays alive as long as your class instance exists.
Consider this example:
UCLASS()
class AMyGameActor : public AActor
{
GENERATED_BODY()
public:
// This is safe! The GC knows this object is being referenced.
UPROPERTY()
AActor* MyTrackedActor;
// DANGER! The GC ignores this pointer. If the object it points
// to is destroyed elsewhere, this becomes a dangling pointer.
AActor* MyUnsafePointer;
};
By simply adding that UPROPERTY() tag, you create a "strong reference." This tells the engine to track the lifecycle of the referenced object, preventing it from being swept away while you still need it. This is a foundational practice for building stable, crash-free gameplay systems in Unreal Engine.
Key Takeaway: Always use the UPROPERTY() macro on pointers to UObjects to register them with the Garbage Collector and prevent your pointers from becoming dangerous, dangling references.