Shared Pointers

Choose your OS:

A shared pointer is a fancy type of non-intrusive, reference-counted smart pointer that supports both strong and weak references. Shared pointers inherently include all the benefits of basic smart pointers in that they prevent memory leaks, uninitialized memory, etc., but also bring additional features, such as:

  • Shared ownership - reference counting

  • Automatic invalidation - volatile objects can be safely referenced

  • Weak references - allows avoidance of cycles via Weak Pointers

  • Improved indication of programmer intent - distinguishes owners from observers and provides non-nullable references ( Shared References )

Some other basic characteristics of shared pointers:

  • Very robust syntax

  • Non-intrusive (but reflection is possible)

  • Thread-safe (conditionally)

  • Good performance, light on memory

Declaration and Initialization

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

Examples of creating new shared pointers:

// Create an empty shared pointer
TSharedPtr<FTreeNode> EmptyNode;

// Create a shared pointer to a new object
TSharedPtr<FTreeNode> Node( new FTreeNode() );

In the second example, the new FTreeNode object is actually owned by the shared pointer pointing to it. When the shared pointer goes out of scope, the object is destroyed.

When you copy a shared pointer, a reference to the object being pointed to is added.

TSharedPtr<FTreeNode> OtherNodeRef = Node;

The object will persist until no more shared pointers are referencing it.

Shared pointers can be reset using the Reset() method or by assigning null.

Node = null;

Dereferencing and Accessing

Dereferencing, calling methods, and accessing members is done in the same manner you would with regular C++ pointers.

( *Node ).ListChildren();


Shared pointers can be tested for equality, i.e. whether they point to the same object.

TSharedPtr<FTreeNode NodeA, NodeB;

if( NodeA == NodeB )

Shared pointers can be tested for null by using the IsValid() method or accessing the raw pointer and performing a comparison.

if( Node.IsValid() )

if( Node.Get() != null )


Implicit conversion is not allowed as it is extremely dangerous. For example, the following will not compile:

TSharedPtr<float> Height = 45.0f;

However, the MakeShareable() method can be used to be explicit.

TSharedPtr<float> Height = MakeShareable( new float( 45.0f ) );