TObjectPtr
TObjectPtr는 UE5에서 도입된 스마트 포인터로 주로 UObject 타입을 객체를 안전하게 참조하기 위해 사용된다.
TObjectPtr는 가비지 컬렉션 시스템과 긴밀하게 연관되어 있어 다음과 같은 이점을 제공한다.
I. 가비지 컬렉션 통합
가비지 컬렉션 시스템과 통합되어 있어, 객체가 가비지 컬렉션에 의해 해제될 때 자동으로 nullptr로 설정된다.
이는 댕글링 포인터 문제를 방지하고, 객체의 유효성을 안전하게 관리할 수 있도록 도와준다.
II. 안전한 참조 관리:
TObjectPtr은 객체의 유효성을 보장하기 위해, 객체가 삭제되면 자동으로 nullptr로 설정된다
이는 참조된 객체가 삭제된 후에도 안전하게 포인터를 사용할 수 있게 한다.
TObjectPtr 사용법
TObjectPtr를 사용하는 방법은 일반 포인터와 유사하지만, 더 안전하고 가비지 컬렉션과
통합되어 있다는 점에서 다르다.
다음은 TObjectPtr의 사용법과 예제이다.
기본 사용법
I.객체 생성 및 참조
TObjectPtr는 UObject를 상속받는 클래스의 객체를 참조하는데 사용된다.
객체는 NewObject 함수를 통해 생성된다.
TObjectPtr<MyClass> MyObjectPtr = NewObject<MyClass>();
II. 객체 사용
TObjectPtr를 통해 객체의 멤버 함수나 변수에 접근할 수 있다.
if (MyObjectPtr)
{
MyObjectPtr->MyFunction();
}
III. 객체 유효성 검사
객체가 가비지 컬렉션에 의해 삭제된 경우, TObjectPtr는 자동으로 nullptr로 설정된다.
이를 통해 객체의 유효성을 쉽게 검사할 수 있다
if (!MyObjectPtr)
{
UE_LOG(LogTemp, Warning, TEXT("MyObjectPtr is null."));
}
IV. 예제
다음은 TObjectPtr를 사용하게 객체를 생성, 사용, 그리고 가비지 컬렉션을 통한 메모리 관리를 보여주는 예제이다.
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyClass.generated.h"
UCLASS()
class MYPROJECT_API AMyClass : public AActor
{
GENERATED_BODY()
public:
void MyFunction()
{
UE_LOG(LogTemp, Warning, TEXT("MyFunction called"));
}
};
void ExampleFunction()
{
// TObjectPtr를 사용하여 MyClass 객체 생성
TObjectPtr<AMyClass> MyObjectPtr = NewObject<AMyClass>();
// MyObjectPtr가 가리키는 객체 사용
if (MyObjectPtr)
{
MyObjectPtr->MyFunction();
}
// 가비지 컬렉션 강제 실행
CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS, true);
// 객체가 가비지 컬렉션에 의해 해제되면 MyObjectPtr는 nullptr로 설정됨
if (!MyObjectPtr)
{
UE_LOG(LogTemp, Warning, TEXT("MyObjectPtr is null after garbage collection."));
}
}
객체를 생성하고 사용하는 예제
MyClass.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyClass.generated.h"
UCLASS()
class MYPROJECT_API AMyClass : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMyClass();
// Example function that prints a message
void MyFunction() const;
};
MyClass.cpp
#include "MyClass.h"
#include "Engine/Engine.h"
// Sets default values
AMyClass::AMyClass()
{
PrimaryActorTick.bCanEverTick = true;
}
// Example function that prints a message
void AMyClass::MyFunction() const
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, TEXT("MyFunction called"));
}
}
MyGameMode.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "MyClass.h"
#include "MyGameMode.generated.h"
UCLASS()
class MYPROJECT_API AMyGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
// Sets default values for this game mode's properties
AMyGameMode();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
// TObjectPtr to manage MyClass instance
TObjectPtr<AMyClass> MyObjectPtr;
};
MyGameMode.cpp
#include "MyGameMode.h"
#include "Engine/Engine.h"
// Sets default values
AMyGameMode::AMyGameMode()
{
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMyGameMode::BeginPlay()
{
Super::BeginPlay();
// Create an instance of MyClass and store it in MyObjectPtr
MyObjectPtr = NewObject<AMyClass>();
// Use MyObjectPtr to call a function on MyClass
if (MyObjectPtr)
{
MyObjectPtr->MyFunction();
}
// Simulate garbage collection to show how MyObjectPtr handles it
CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS, true);
// Check if MyObjectPtr is still valid after garbage collection
if (!MyObjectPtr)
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("MyObjectPtr is null after garbage collection."));
}
}
}
- MyClass.h와 MyClass.cpp : AMyClass 클래스 정의와 구현을 포함한다.
- AMyClass는 AActor 를 상속받고 있으며, MyFunction이라는 예제함수를 제공한다.
- MyGameMode.h와 MyGameMode.cpp : AMyGameMode 클래스에서 TObjectPtr<AMyClass>를 사용하여 AMyClass의 인스턴스를 관리한다. BeginPlay 함수에서 객체를 생성하고 사용한 후 가비지 컬렉션을 싱행하여 포인터가 안전하게 처리되는지 확인한다.
'Unreal Engine' 카테고리의 다른 글
[UE5] DECLARE_ATTRIBUTE_CAPTUREDEF (0) | 2024.05.28 |
---|---|
[UE5] ActivateAbility (0) | 2024.05.18 |
[UE5] AActor (0) | 2024.05.14 |
[UE5] 속성 기반 수정자 (0) | 2024.04.16 |
[UE5] GAS(GameplayAbilitySystem) I (0) | 2024.03.25 |