Memory
A explanation of the few different memory management systems in Unreal Engine: Garbage Collection, Smart Pointers, alias Standard C++ Memory Management.
Overview
Unreals game-level memory management system uses reflection to implement garbage collection. Working effectively in Unreal requires some understanding of how these two systems interact.
What is reflection?
Inform yourself about Unreals (Reflection) Property System and how to use it. Reflection allows the engine to determine if objects are still referenced by other objects, making garbage collection a viable strategy for managing memory.
Garbage Collection
Concept
One of the most important tasks within a game engine is managing memory. Unreals approach to solve this problem is the usage of garbage collection. In this approach, the engine will automatically delete objects when they are no longer needed. An object is no longer needed when it is no longer referenced by any other object. If you are more curious about Garbage Collection, visit garbage collection–computer science.
Unreal uses the reflection system to drive garbage collection. Because the engine knows about your objects and properties, it can recognize when an object is no longer needed and automatically delete it.
While this automatic memory management does significantly reduce the mental workload to working in the engine, it is important to understand at a high level how it works, as it can only work well when you follow the rules.
Declaration
UPROPERTY
Its recommended to declare evey member of a class UPROPERTY, if an member is left naked Unreal Engine won't know about it. So, an object you are pointing at could get deleted out from under you! It's safe to leave value types such as an int or a bool naked although they could not be saved, replicated, or appear in the editor.TArray
TArrayis the only container that is safe to have pointers in
Usage
Garbage Collection (UObject*, TWeakObjectPtr, TSoftObjectPtr) is a automatic memory management system exclusive for Unreal Objects that tracks UObject sub-classes, which include AActor and UActorComponent. Unreal Engine will automatically add newly created UObjects to its internal objects list, so even with improper use it's not easy to have memory leaks, but it is easy to cause crashes.
UObjects should never be created with new, but only with the default creation methods (NewObject, SpawnActor, CreateDefaultSubobject)
Objects are primarily kept alive in 3 ways:
By having a strong reference (UPROPERTY) to them (from objects that are also referenced)
By calling
UObject::AddReferencedObjects(from objects that are also referenced)By adding them to the root set with
UObject::AddToRoot(typically unnecessary)
When objects do not fulfill any of the above conditions, on the next GC cycle they will be marked as unreachable and garbage collected (destroyed). Passing an object as an Outer to another object does not automatically mean the other object will be kept alive, the same goes for default subobjects. To force the destruction of objects that are still reachable, you can call MarkPendingKill on them, and it will force their destruction on the next GC cycle.
Destruction of an object doesn't necessarily all happen in the same frame, when garbage collection starts on it, it will first call BeginDestroy (do not call this yourself), then, when ready FinishDestroy. The GC runs in the game thread so you can trust that it won't clean up an object within the lifetime of a function. While the most common way of keeping objects alive is through a UPROPERTY, actors and components work differently:
Levels reference their actors and actors reference their components. Both work by overriding the UObject::AddReferencedObjects implementation and collecting what they do not want to be garbage collected. This means that even if there are no strong references to level actors and components, they won't be garbage collected until manually destroyed, or their level is unloaded.
Garbage collector will automatically clear the following references to garbage collected objects:
Raw pointers declared with
UPROPERTY, will be set to nullptrRaw pointers in
UObjectcompatible containers declared withUPROPERTY(such asTArray,TSetorTMap), the affected elements will be set as nullptr but not removed
Whenever code references an AActor or a UActorComponent, it has to deal with the possibility that AActor::Destroy could be called on the actor or UActorComponent::DestroyComponent could be called on the component. These functions will mark them for pending kill, thus triggering their garbage collection at the first opportunity (note that destroying an actor also destroys all its components).
Since the garbage collector automatically nulls out UPROPERTY pointers when it actually gets to destroy them, null-checking an actor or component pointer is sufficient to know it's safe to use, though you might also want to check IsPendingKill on them to avoid accessing them after they have been marked for destruction (TWeakObjectPtr already checks for this when retrieving the raw pointer).
bool IsValid(const UObject* Test)
is a global function that automatically checks if an object pointer is non-null and not pending kill.
UObjectBase::IsValidLowLevel
UObjectBase::IsValidLowLevelFast
Should not be used for Garbage Collection checks, as on UPROPERTY pointers it will always return true, while on raw pointer it will return true or false depending whether the object had already been destroyed, but in the latter case it's also likely to also crash the application as the pointed memory could have been overwritten.
If you write your own non-garbage classes that references garbage collected objects, you may want to sub-class FGCObject.
Unreal Smart Pointer Library
Unreal Smart Pointers (TUniquePtr, TSharedPtr, TWeakPtr) is a smart memory management system, for code that is not based on the Unreal Object system, designed to ease the burden of memory allocation and tracking. It also adds TSharedRef, which acts like a non-nullable Shared Pointer. Unreal Smart Pointers cannot be used with Unreal Objects, because they use a separate memory-tracking system that is better-tuned for game code.
Structs vs. Objects
Structures are intended for use as 'value' types. They are best suited for small amounts of data to be reused in objects and actors. For example, FVector, FRotator, FQuat. They are not deleted, so they must always exist within a UObject.
One advantage of UStructs is that they are very small. While a UObject must contain accounting data in addition to your data, UStructs (technically UScriptStructs) are only as large as the data you store in them. The garbage collector doesn't have to do as much work to manage them.
UObjects are collected by the garbage collector. Although they are heavier, it is generally safe to point to them. Keep in mind that each UObject is another thing for the garbage collector to keep track of. Although the engine can easily handle thousands of objects, this capability should be used carefully. If your project requires thousands of instances of something and UStructs are acceptable, they will generally be more powerful than UObjects.
Containers
For the garbage collector to do its work of determining what is safe to delete, it must traverse every field of every object. While Unreal provides several types of containers (TArray, TMap, …) the garbage collector only considers pointers in TArray.
See Also
Some more specifics and code examples related to memory management, see Dynamic Memory Allocation.