In this lesson, you will learn how to use TSharedRef to guarantee that your pointers are never null, providing a safer and more efficient alternative to TSharedPtr.
Understanding TSharedRef
When you use TSharedPtr, you frequently have to write "defensive code" to check if the pointer is valid before accessing it. You’ve likely written many if (MyPtr.IsValid()) blocks to prevent crashes. While TSharedPtr is excellent for objects that might not exist, it carries the slight overhead of these existence checks and the potential for null pointer dereference errors.
TSharedRef is essentially a TSharedPtr that is guaranteed to be non-nullable. By design, you cannot create a TSharedRef from a null object, and you cannot set one to null. Because the compiler and the engine know for certain that the object exists, you skip the need for constant validity checks, leading to cleaner and slightly more performant code.
When to Use It
Use TSharedRef when you have a piece of data that must exist for your logic to function. If your system depends on a configuration object or a data provider that is initialized once and never destroyed until the owner is destroyed, TSharedRef is the perfect tool.
Here is how you initialize and use one:
// Creating a TSharedRef (MakeShared is preferred)
TSharedRef<FMyData> DataRef = MakeShared<FMyData>();
// Accessing the object is safe and direct
DataRef->DoSomething();
// You can easily convert a TSharedRef to a TSharedPtr if needed
TSharedPtr<FMyData> DataPtr = DataRef;
Why it Matters
By forcing this requirement at compile-time, you move the responsibility of checking for nulls away from your runtime logic. When you pass a TSharedRef to a function, the function signature itself acts as a contract: the caller is promising that the object is valid. This prevents entire classes of bugs where a pointer is accidentally passed as null, and it keeps your inner-loop logic fast by removing unnecessary branching.
Key Takeaway: Use TSharedRef when you want to enforce non-null safety and eliminate the performance cost of validity checks by guaranteeing your object instance exists.