In this lesson, you will learn how to use TUniquePtr to enforce exclusive ownership of non-UObject resources, ensuring they are automatically cleaned up when they go out of scope.
The Problem with Manual Memory
Up until now, we have relied heavily on Unreal’s Garbage Collection (GC) for UObject types. However, when you need to use standard C++ objects—like a custom data parser, a complex mathematical helper, or a third-party library wrapper—these objects are invisible to the Garbage Collector. If you use a raw pointer (e.g., MyClass* Obj = new MyClass();), you are responsible for calling delete manually. If you forget, you create a memory leak; if you delete it too early, you create a crash.
Enter TUniquePtr
TUniquePtr is a smart pointer that embodies the concept of "exclusive ownership." When you wrap a resource in a TUniquePtr, you are declaring that this specific variable is the only owner of that object.
Because it is "unique," you cannot copy it—you can only move it. When the TUniquePtr variable goes out of scope (for example, at the end of a function or when its parent class is destroyed), it automatically calls the destructor on the object it points to.
Practical Implementation
Imagine you are building a custom file-processing system that isn't a UObject:
// Inside your class header
#include "Templates/UniquePtr.h"
class FMyManager {
// Unique ownership: no need to call 'delete' manually!
TUniquePtr<FFileProcessor> Processor;
void Initialize() {
Processor = MakeUnique<FFileProcessor>();
}
};
In this example, as soon as FMyManager is destroyed, the Processor member is automatically destroyed as well. You don't have to worry about cleaning it up in BeginDestroy or tracking its lifetime across complex logic.
Because TUniquePtr is not a UObject, you should never use it to hold a pointer to a UObject, as it will not play nice with Unreal’s Garbage Collector. It is designed specifically for raw C++ memory management where you want deterministic, immediate cleanup.
Key Takeaway: Use TUniquePtr for non-UObject resources to guarantee automatic memory cleanup and prevent leaks by enforcing a strict "one owner" policy.