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

Managing UObject References with TWeakObjectPtr

Use TWeakObjectPtr to safely track UObjects that may be garbage collected, preventing dangling pointers by checking validity before accessing the underlying object.

In this lesson, you will learn how to safely reference UObject instances without preventing them from being garbage collected by using TWeakObjectPtr.

The Problem: Dangling Pointers

As you know, Unreal’s Garbage Collector (GC) runs periodically to reclaim memory from objects that are no longer referenced. If you store a raw C++ pointer to a UObject and the GC deletes that object, your pointer becomes "dangling"—it points to a memory address that no longer contains valid data. Accessing this pointer will cause your game to crash immediately.

While UPROPERTY() creates a strong reference that tells the GC "don't delete this," sometimes you want to observe an object without owning it. This is where TWeakObjectPtr comes in.

Using TWeakObjectPtr

A TWeakObjectPtr acts like a "safe" pointer. It doesn't prevent the GC from deleting the object, but it is "smart" enough to know when the object it points to has been destroyed.

Here is how you implement it:

// Define the weak pointer in your header
TWeakObjectPtr<AActor> TargetActor;

// Later, in your logic, check if the object still exists
if (TargetActor.IsValid())
{
    // It is safe to access the object now
    TargetActor->DoSomething();
}
else
{
    // The object was garbage collected, handle the scenario safely
    UE_LOG(LogTemp, Warning, TEXT("The actor has been destroyed!"));
}

Why it works

When you call IsValid(), the TWeakObjectPtr checks the internal GC tracking system to see if the underlying UObject has been marked for deletion or cleared. If the object is gone, IsValid() returns false, and the pointer automatically nulls itself out. This prevents you from ever attempting to dereference a stale memory address.

This is particularly useful for systems like UI widgets tracking a target, or projectiles tracking an enemy that might be destroyed mid-flight. By using a weak pointer, you ensure that your code remains robust even when the objects it depends on are dynamic and temporary.

Key Takeaway: Use TWeakObjectPtr to reference UObjects you don't own, ensuring you can always verify if the object still exists before attempting to access it.