Garbage Collection & TObjectPtr
UObjects are not freed with delete. Unreal has a garbage collector: every so often (by default about once a minute, plus at level transitions, configurable with gc.TimeBetweenPurgingPendingKillObjects), it finds the objects nothing references any more and destroys them. To find references it uses reflection: it only follows pointers stored in UPROPERTY members (and a few other registered places). A pointer it can't see doesn't keep the object alive, and doesn't get cleaned up when the object dies.
Mark and sweep
Unreal's collector is a mark-and-sweep collector:
- Mark: start from the root set (objects added with
AddToRoot(), the engine's core objects, the loaded world and level, and through them every actor in a level). Follow every reflected object reference (UPROPERTYpointers,TArray<TObjectPtr<…>>, maps, structs) and mark each object reached. - Sweep: every object not marked is unreachable. It gets
BeginDestroy/FinishDestroyand its memory is freed.
Actors are a special case: a spawned actor is referenced by its level, so it stays alive until you call Destroy(). Destroying it removes it from the level; the GC frees it later, and sets reflected pointers to it to null when it does. Plain UObjects created with NewObject stay alive only as long as something reachable references them.
A runnable model: why the raw pointer dangles
This model has objects in a pool of slots. References come in two kinds: UPROPERTY references the collector traces, and raw pointers it doesn't know about. A freed slot is reused by the next allocation, just as real memory is.
#include <iostream>
#include <string>
#include <vector>
struct Object {
std::string Name;
bool Alive = false, Marked = false;
std::vector<int> UProperties; // traced references (slot indices)
};
std::vector<Object> Heap(4);
std::vector<int> RootSet;
int NewObject(const std::string& name) {
for (int i = 0; i < (int)Heap.size(); i++)
if (!Heap[i].Alive) { Heap[i] = Object{name, true, false, {}}; return i; }
return -1;
}
void Mark(int i) {
if (i < 0 || !Heap[i].Alive || Heap[i].Marked) return;
Heap[i].Marked = true;
for (int ref : Heap[i].UProperties) Mark(ref);
}
void CollectGarbage() {
for (auto& o : Heap) o.Marked = false;
for (int r : RootSet) Mark(r);
for (auto& o : Heap) {
if (o.Alive && !o.Marked) { std::cout << " GC frees " << o.Name << "\n"; o.Alive = false; }
else if (o.Alive) { // null out traced references to freed objects
for (int& ref : o.UProperties)
if (ref >= 0 && !Heap[ref].Alive) ref = -1;
}
}
}
int main() {
int level = NewObject("Level");
RootSet.push_back(level);
int hero = NewObject("Hero");
Heap[level].UProperties.push_back(hero); // the level references its actors
int buffA = NewObject("SpeedBuff");
Heap[hero].UProperties.push_back(buffA); // UPROPERTY() TObjectPtr<UBuff> ActiveBuff;
int buffB = NewObject("ShieldBuff");
int rawShield = buffB; // UBuff* CachedShield; (no UPROPERTY!)
std::cout << "GC pass 1\n";
CollectGarbage();
std::cout << " SpeedBuff alive: " << Heap[buffA].Alive << "\n";
std::cout << "something else is allocated\n";
int fx = NewObject("ExplosionFX"); // reuses the freed slot
std::cout << " ExplosionFX got slot " << fx << ", CachedShield points to slot " << rawShield << "\n";
std::cout << " hero calls CachedShield->Name: " << Heap[rawShield].Name << " <- wrong object!\n";
}GC pass 1
GC frees ShieldBuff
SpeedBuff alive: 1
something else is allocated
ExplosionFX got slot 3, CachedShield points to slot 3
hero calls CachedShield->Name: ExplosionFX <- wrong object!
SpeedBuff survived because the hero's UPROPERTY reference was traced. ShieldBuff was only held by a raw pointer, so the collector saw nothing referencing it and freed it. The raw pointer still held the old address, and once that memory was reused it pointed at an unrelated object. In the real engine this is a crash in the best case, and memory corruption that shows up minutes later in the worst.
The rules
UCLASS()
class ARENA_API AArenaHero : public ACharacter
{
GENERATED_BODY()
// ✔ traced: keeps the buff alive, nulled if the object is destroyed
UPROPERTY()
TObjectPtr<UArenaBuff> ActiveBuff;
// ✔ containers of object pointers are traced too
UPROPERTY()
TArray<TObjectPtr<UArenaBuff>> Buffs;
// ✔ a reference that must NOT keep the target alive (next lesson)
TWeakObjectPtr<AActor> LastAttacker;
// ✘ invisible to the GC: may dangle
UArenaBuff* CachedShield = nullptr;
};- Every
UObject*member of aUObjectclass getsUPROPERTY(), even with no specifiers. In UE5 write members asTObjectPtr<T>. It behaves like a raw pointer, adds access tracking in editor builds, and is the recommended member type. - Function parameters and locals stay raw pointers (
UArenaBuff* Buff). They live for one call; the GC doesn't run in the middle of your function. - Plain C++ classes that hold
UObjects (a non-UObject manager, a Slate widget) derive fromFGCObjectand report their references inAddReferencedObjects, or hold aTStrongObjectPtr<T>. - Never
deletea UObject. For actors callDestroy(). For other objects drop your references and let the GC run.MarkAsGarbage()exists for objects you know are finished (it replaced UE4'sMarkPendingKill).
// A non-UObject class that holds UObjects
class FArenaBuffCache : public FGCObject
{
public:
TArray<TObjectPtr<UArenaBuff>> Cached;
virtual void AddReferencedObjects(FReferenceCollector& Collector) override
{
Collector.AddReferencedObjects(Cached);
}
virtual FString GetReferencerName() const override { return TEXT("FArenaBuffCache"); }
};Debugging GC problems
obj gc/gc.CollectGarbageEveryFrame 1in the console forces collection every frame. It makes the game slow, but turns a once-a-minute crash into an immediate one, close to the code that caused it.obj refs name=MyObjectNameprints the reference chain keeping an object alive, for the opposite problem: a leak.- A crash in
FGCObjectcode, or one that happens "about once a minute", is a GC suspect until proven otherwise.
Test yourself
Which member keeps a UObject alive through garbage collection?
UArenaBuff* Buff;UPROPERTY() TObjectPtr<UArenaBuff> Buff;std::shared_ptr<UArenaBuff> Buff;TWeakObjectPtr<UArenaBuff> Buff;
Why did the raw pointer in the model end up pointing at ExplosionFX?
- The GC moved the object
- The shield was freed because nothing traced referenced it, and its memory was reused
- Raw pointers are always null after GC
- ExplosionFX was spawned at the same location
How do you free an actor you no longer need?
delete Actor;Actor->Destroy();and let GC reclaim itActor->BeginDestroy();- Set all pointers to nullptr