Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท C++ Gameplay

Memory and Garbage Collection in Unreal C++

Understand how Unreal Engine manages memory. UObject garbage collection, UPROPERTY references, TObjectPtr, TWeakObjectPtr, TSharedPtr and when to use each.

C++ gives you manual memory control, and manual control means leaks and dangling pointers. Unreal Engine softens this with its own garbage collector (GC) for UObject-derived types, and offers smart pointers for everything else. Knowing which tool applies to which type is one of the most important skills in Unreal C++.

The engine cannot run on this site, so the C++ here is read-only. The Python stand-ins model the ideas, in particular a tiny mark-and-sweep collector.

Two worlds of memory

Kind of type Examples Who frees it
UObject types AActor, UActorComponent, UDataAsset, UUserWidget The garbage collector
Plain C++ types FString, TArray, FMyStruct, your own classes Scope, delete, or smart pointers

UObjects are never created with new or deleted with delete. You create them with NewObject<T>(), CreateDefaultSubobject<T>() (in constructors) or SpawnActor<T>(), and you stop referencing them.

How the garbage collector decides

Periodically (every 60 seconds by default, and at level changes) the GC runs mark and sweep:

  1. Start from root objects, such as the engine, the current world and anything added to the root set.
  2. Follow every reflected reference, meaning any UPROPERTY pointer, TArray<UObject*> inside a UPROPERTY, and so on.
  3. Everything reached is marked alive.
  4. Everything unmarked is destroyed.

The crucial consequence: a UObject* that is not a UPROPERTY is invisible to the GC. Nothing keeps its target alive, and when the target is collected your pointer dangles.

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

    UPROPERTY()
    TObjectPtr<UMyThing> Safe;   // GC sees it: the object stays alive

    UMyThing* Dangerous;         // GC does not see it: can become a dangling pointer
};

Actors are special: they are owned by the world and stay alive until destroyed with Destroy() (marked pending kill and then collected) or until the level ends.

Pointer types you will use

TObjectPtr<T> is the member-variable pointer type for UObjects since UE5. It behaves like T* but supports editor features such as lazy loading and access tracking. Use it for UPROPERTY members, and raw T* for function parameters and locals.

TWeakObjectPtr<T> does not keep the object alive and becomes invalid when the object is destroyed. Always check before use:

C++
TWeakObjectPtr<AActor> Target;

if (Target.IsValid())
{
    Target->Destroy();
}

TSoftObjectPtr<T> and TSoftClassPtr<T> hold a path to an asset that may not be loaded. They are the tool for avoiding hard references that pull a whole asset chain into memory; load them with LoadSynchronous() or the asynchronous streamable manager.

TSubclassOf<T> holds a class (not an instance) restricted to T and its children. It is how you expose "which Blueprint to spawn" in the Details panel:

C++
UPROPERTY(EditDefaultsOnly)
TSubclassOf<AProjectile> ProjectileClass;

GetWorld()->SpawnActor<AProjectile>(ProjectileClass, Location, Rotation);

TSharedPtr<T>, TSharedRef<T>, TUniquePtr<T> are for non-UObject types, with the same meaning as the standard library versions. Never wrap a UObject in them.

Checking validity

An Actor can be destroyed but still referenced by something else. Use these checks:

  • IsValid(Object) is true when the pointer is non-null and the object is not pending destruction. Prefer it to a plain if (Object).
  • IsValid() on weak pointers does the same job.
  • Object->IsPendingKillPending() is rarely needed directly.

A model of mark and sweep

Python Stand-in: a tiny mark-and-sweep collector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The weapon survives the first pass because player still references it, and is destroyed after the reference is cleared.

Dangling vs weak pointers

Python Stand-in: weak pointer protects against destroyed objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(Python's reference counting frees the object immediately, whereas Unreal waits for the next GC pass; the idea of checking a weak handle before use is the same.)

Common mistakes

  • Unreflected UObject* members. The most common source of random crashes. Add UPROPERTY().
  • Hard references everywhere. A TSubclassOf or TObjectPtr to a big Blueprint loads it whenever your class loads. Use soft pointers for optional content.
  • new/delete on UObjects. Never. Use NewObject.
  • Caching an Actor in a plain struct. Structs outside UPROPERTY are invisible to the GC; use weak pointers there.
  • Using a pointer after Destroy() in the same frame. Check IsValid.

See Delegates, timers and spawning for the next topic, where weak references matter again.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a plain UObject* member without UPROPERTY dangerous?

    Only reflected references are traced during the mark phase; unreflected pointers do not keep objects alive.
  2. 2. Which pointer should you use to refer to an Actor without keeping it alive?

    TWeakObjectPtr does not prevent collection and reports invalid once the object is destroyed.
  3. 3. What is TSubclassOf<AProjectile> used for?

    TSubclassOf holds a class reference restricted to a type hierarchy, so you can choose a Blueprint in the Details panel.
  4. 4. How are UObjects created in C++?

    UObjects are allocated through engine functions so the garbage collector can track them.

Summary

  • UObjects are collected by mark and sweep; reflected references keep them alive.
  • Mark member pointers with UPROPERTY and prefer TObjectPtr for members.
  • Use TWeakObjectPtr for non-owning references and TSoftObjectPtr to avoid loading assets early.
  • TSharedPtr and friends are for non-UObject types only.
  • Check IsValid before using an object that may have been destroyed.

Next: Delegates, Timers and Spawning