You've already forked UnrealEngineUWP
mirror of
https://github.com/izzy2lost/UnrealEngineUWP.git
synced 2026-03-26 18:15:20 -07:00
55 lines
2.4 KiB
Plaintext
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.5
|
|
|
|
[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]
|