AgentSkillsCN

Cpp Memory Management

运用UE5指针、内存分配或对象生命周期管理。

SKILL.md
--- frontmatter
description: Working with UE5 pointers, memory allocation, or object lifecycle

UE5 C++ Memory Management

Proper memory management in Unreal Engine requires understanding the garbage collection system.

UObject Pointers

Always use UPROPERTY() for UObject pointers - this enables garbage collection tracking.

cpp
// CORRECT - GC will track this reference
UPROPERTY()
UStaticMeshComponent* MeshComponent;

UPROPERTY()
TObjectPtr<UStaticMeshComponent> MeshComponent;  // UE5 preferred

// WRONG - GC cannot track, may cause crashes
UStaticMeshComponent* MeshComponent;  // Raw pointer without UPROPERTY
TSharedPtr<UStaticMeshComponent> MeshComponent;  // Never use smart pointers for UObjects!

Smart Pointers (Non-UObjects Only)

TypeUse Case
TSharedPtr<T>Shared ownership of non-UObject
TWeakPtr<T>Non-owning reference, break circular refs
TUniquePtr<T>Exclusive ownership of non-UObject
TObjectPtr<T>UPROPERTY UObject references (UE5)
cpp
// For non-UObject types only
TSharedPtr<FMyCustomStruct> SharedData;
TWeakPtr<FMyCustomStruct> WeakRef;
TUniquePtr<FMyCustomStruct> UniqueData;

Object Creation

cpp
// Runtime object creation (outside constructors)
UMyComponent* Comp = NewObject<UMyComponent>(this);

// Constructor only - creates default subobjects
USceneComponent* Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));

Rules

RuleReason
UPROPERTY() for all UObject pointersGC tracking
TSharedPtr/TWeakPtr for non-UObjects onlyGC doesn't understand smart pointers
NewObject<T>() at runtimeProper GC registration
CreateDefaultSubobject<T>() in constructors onlyCDO creation semantics
TWeakPtr to break circular referencesPrevent memory leaks
Never AsShared/SharedThis in constructorsObject not fully constructed
Pass as const& not smart pointerPerformance optimization

Common Mistakes

cpp
// WRONG - Smart pointer for UObject
TSharedPtr<AActor> MyActor;

// WRONG - CreateDefaultSubobject outside constructor
void BeginPlay()
{
    Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
}

// WRONG - Raw pointer without UPROPERTY
AActor* CachedTarget;  // May become invalid after GC

Correct Patterns

cpp
UPROPERTY()
TObjectPtr<AActor> CachedTarget;  // UE5 style

// Check validity before use
if (IsValid(CachedTarget))
{
    // Safe to use
}

Documentation: https://dev.epicgames.com/documentation/en-us/unreal-engine/unreal-object-handling-in-unreal-engine