Memory Management

There are a few different memory management systems in UE4's C++ implementation: garbage collection, smart pointers, and standard C++ memory management. Garbage Collection Garbage collection tracks...

Updated over 3 years ago

There are a few different memory management systems in UE4's C++ implementation: 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.

Actors

Anytime code references an AActor, it has to deal with the possibility that

AActor::Destroy

is called on that actor, which will garbage collect the actor.

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

References

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