Smart Pointers
Related Docs
Unreal has its own implementation of C++11 Smart Pointers to ease the burden of memory allocation and tracking for non-UObject
classes. They work through reference counting and can help prevent memory leaks at the cost of a small overhead.
TUniquePtr<T>
are Unique Smart Pointers, which solely and explicitly owns the object it references. They can transfer ownership, but cannot share it. Any attempts to copy a Unique Pointer will result in a compilation error. When it goes out of scope, it will delete the object it references.
TUniquePtr<FMyObjectType> NewPointer(new FMyObjectType(...));
TSharedPtr<T>
are Shared Smart Pointers, which increment the counter and prevent the deletion of the object as long as the pointer exists. They can be created from an existing pointer or by using the MakeShared
function, which allocates the object and the counter in a single memory block.
TSharedPtr<FMyObjectType> NewPointer(new FMyObjectType(...));
TSharedPtr<FMyObjectType> AnotherPointer = MakeShared<FMyObjectType>(...);
TSharedRef<T>
are Shared Smart References, which similar to shared pointers, but they are not nullable. Assigning nullptr
to a shared reference will lead to a compilation error or an assertion error.
TSharedRef<FMyObjectType> NewReference(new FMyObjectType());
TSharedRef<FMyObjectType> AnotherReference = MakeShared<FMyObjectType>();
TWeakPtr<T>
are Weak Smart Pointers, which do not increment the counter and will not prevent the deletion of the object. By calling the Pin()
method, they can be converted to a shared pointer, to keep the object alive.
TWeakPtr<FMyObjectType> ObserverInstance(OriginalInstance);
TWeakPtr<FMyObjectType> AnotherObserver = OriginalInstance;
The reference counting mechanism can be performed in a thread-safe manner. Note that there is no internal lock to control access to the referenced data and writes and resets still need to be synchronized.
TSharedPtr<T, ESPMode::ThreadSafe> SharedPtr;
TSharedRef<T, ESPMode::ThreadSafe> SharedRef;
TWeakPtr<T, ESPMode::ThreadSafe> WeakPtr;