Files
UnrealEngineUWP/Engine/Documentation/Source/Programming/UnrealArchitecture/SmartPointerLibrary/SharedReference/SharedReference.INT.udn
Matthew Clark 0061a4e8eb #UE4doc #docs:
Updated engine version
Changed font settings for multiple terms
Changed all mentions of NULL to null to reflect changes made to the engine.

[CL 2622058 by Matthew Clark in Main branch]
2015-07-15 13:55:37 -04:00

55 lines
2.4 KiB
Plaintext

Availability:Public
Title:Shared References
Crumbs:%ROOT%, Programming, Programming/UnrealArchitecture/SmartPointerLibrary
Description:Smart pointer type that cannot be uninitialized or assigned null.
Version: 4.9
[TOC(start:2)]
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 [](Programming/UnrealArchitecture/SmartPointerLibrary/SharedPointer) 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();
[REGION:note]
In a similar manner to the * operator with C++ pointers, using ToSharedRef() will assert if the object is not valid.
[/REGION]