Shared References

A shared reference is a non-nullable shared pointer. This means you cannot create an empty shared reference and you cannot assign null to a shared reference, which helps you write safer, cleaner code since you know it is safe to access the object. In fact, shared references do not even have an IsValid() method - like shared pointers do - since they are always valid. It is recommended to always use shared references instead of shared pointers when possible.

If you need empty/nullable references, you should use Shared Pointers instead.

Declaration and Initialization

Shared references are always initialized with a valid object and cannot be declared without being initialized.

An example of creating a new shared reference:

// Create a shared reference to a new node
TSharedRef<FTreeNode> NodeRef( new FTreeNode() );

Attempting to declare a shared reference without initializing it or assigning null is never allowed:

TSharedRef<UBool> EmptyBool;            // Will not Compile!!

Shared Reference Usage

For the most part, using a shared reference is just like using a shared pointer.

// Create a shared reference to a new node
TSharedRef<FTreeNode> NodeRef( new FTreeNode() );

NodeRef->ListChildren();
( *NodeRef ).ListChildren();
const FTreeNode& NodeVar = NodeRef.Get();

Again, the main difference is that you cannot set a shared pointer to null:

TSharedRef<FTreeNode> Node = null;      // Will not Compile!!

Pointer and Reference Conversion

Shared references convert to shared pointers implicitly so it is always safe to make a pointer from a reference, i.e. you can assign a shared reference to a shared pointer or pass a shared reference to a method expecting a shared pointer.

TSharedPtr<FTreeNode> SomeNodePtr = NodeRef;

However, conversion from a pointer is potentially unsafe, and you are forced to explicitly perform the conversion using the ToSharedRef() function.

// Explicitly reference a pointer. Will assert if the pointer is not valid!
NodeRef = SomeNodePtr.ToSharedRef();

In a similar manner to the * operator with C++ pointers, using ToSharedRef() will assert if the object is not valid.