In this lesson, you will learn how to manually signal the Garbage Collector (GC) to track UObject references held inside non-UObject classes.
The Problem: Invisible References
Normally, the Garbage Collector identifies references by scanning your UPROPERTY() pointers within a UObject. However, if you store a UObject* inside a standard C++ class (a plain-old C++ object that doesn't inherit from UObject), the GC won't know that object is "in use." Consequently, it might delete your object while your C++ class is still holding a pointer to it, resulting in a dangling pointer.
The Solution: FGCObject
To fix this, you use the FGCObject interface. By inheriting from FGCObject, you gain access to the AddReferencedObjects function. This function acts as a "report card" to the Unreal Garbage Collector, telling it exactly which objects you are currently holding.
Here is how you implement it:
class FMyCustomManager : public FGCObject
{
public:
UTexture2D* MyDynamicTexture;
// Override the function to report references
virtual void AddReferencedObjects(FReferenceCollector& Collector) override
{
// Tell the collector: "Please keep this object alive!"
Collector.AddReferencedObject(MyDynamicTexture);
}
// Give the GC a name for this reference (required)
virtual FString GetReferencerName() const override
{
return TEXT("FMyCustomManager");
}
};
How it Works
Whenever the GC runs, it identifies all instances of FGCObject and calls their AddReferencedObjects method. By calling Collector.AddReferencedObject(MyDynamicTexture), you are effectively telling Unreal: "If you are cleaning up memory, do not delete this texture because my class still needs it."
Remember: FGCObject is purely for non-UObject classes. If you are already inside a class that inherits from UObject, you should simply mark your variables with UPROPERTY() instead, as the engine handles that automatically. Using FGCObject is your bridge to keeping UObject life cycles stable when you are working outside the standard reflection system.
Key Takeaway: Inherit from FGCObject and override AddReferencedObjects to prevent the Garbage Collector from destroying UObject references held by plain C++ classes.