Memory Management

There are a few different memory management systems in UE4: garbage collection, smart pointers, and standard C++ memory management. Garbage Collection Garbage collection tracks UObject sub-classes,...

Updated over 3 years ago

There are a few different memory management systems in UE4: garbage collection, smart pointers, and standard C++ memory management.

Garbage Collection

Garbage collection tracks

UObject

sub-classes, which include

[https://docs.unrealengine.com/en-US/API/Runtime/Engine/GameFramework/AActor/index.html AActor]

and

[https://docs.unrealengine.com/en-US/API/Runtime/Engine/Components/UActorComponent/index.html UActorComponent]

.

The garbage collector will clear references to garbage collected objects if the reference is[1]:

  • Declared with
    [https://docs.unrealengine.com/en-US/Programming/UnrealArchitecture/Reference/Properties/index.html UPROPERTY]
    
  • In a
    UObject
    
    compatible container, such as
    TArray
    
    ,
    TSet
    
    , or
    TMap
    
  • In a
    TWeakObjectPtr
    

The garbage collector has a root set of objects which are not collected. Objects are added to the root set with

[https://docs.unrealengine.com/en-US/API/Runtime/CoreUObject/UObject/UObjectBaseUtility/AddToRoot/index.html UObject::AddToRoot]

, although this is typically unnecessary because the level references the actors, and the actor's

UPROPERTY

members reference the

UActorComponent

s. Because levels reference actors spawned into them, actors are only garbage collected when the level is unloaded or

[https://docs.unrealengine.com/en-US/API/Runtime/Engine/GameFramework/AActor/Destroy/index.html AActor::Destroy]

is called.

Anytime code references an

AActor

or

UActorComponent

, it has to deal with the possibility that

AActor::Destroy

is called on that actor, which will garbage collect the actor. Since the garbage collector automatically nulls out references of destroyed objects, a null-check of an actor before it is used is sufficient to know it's safe to use.

If you write your own non-garbage classes that references garbage collected objects, you may want to sub-class FCObject.

Unreal Smart Pointer Library

The Unreal Smart Pointer Library is for code that is not based on the UObject system. It is similar in function to the C++11 standard library smart pointers. Unreal Smart Pointers cannot be used to reference UObjects, because the garbage collector isn't aware of smart pointers[2].

Further reading

Documentation

Other

References

  1. Unreal Object Handling | Automatic Updating of References
  2. Unreal Smart Pointer Library