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,...
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
compatible container, such asUObject
,TArray
, orTSet
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. 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.
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
- Objects - Explanations of the basic gameplay elements, Actors and Objects
- Unreal Object Handling - Overview of the features of the UObject system
- Unreal Smart Pointer Library - Custom implementation of shared pointers, including weak pointers and non-nullable shared references