Created
May 15, 2018 06:28
-
-
Save fortheday/6c1fa9b079ed781352df9c7395835c0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UCLASS() | |
class FORTHEDAYSANDBOX_API UMyObject : public UObject | |
{ | |
GENERATED_BODY() | |
public: | |
virtual void BeginDestroy() override; | |
}; | |
//------------------------------------------------------------------------------ | |
UCLASS() | |
class FORTHEDAYSANDBOX_API AMyActor : public AActor | |
{ | |
GENERATED_BODY() | |
public: | |
virtual ~AMyActor(); | |
private: | |
UPROPERTY() | |
UMyObject *m_pMyObject1; // UPROPERTY | |
UMyObject *m_pMyObject2; // RAW PTR, UNSAFE, BAD USAGE | |
TSharedPtr<UMyObject> m_spMyObject3;// BAD USAGE, TSharedPtr is for FSomethings. | |
protected: | |
virtual void BeginPlay() override; | |
}; | |
//------------------------------------------------------------------------------ | |
// UMyObject | |
//------------------------------------------------------------------------------ | |
void UMyObject::BeginDestroy() | |
{ | |
LOGW("UMyObject::BeginDestroy() %s", *GetFName().GetPlainNameString()); | |
Super::BeginDestroy(); | |
} | |
//------------------------------------------------------------------------------ | |
// AMyActor | |
//------------------------------------------------------------------------------ | |
AMyActor::~AMyActor() | |
{ | |
LOGW("MyObjs: %p, %p", m_pMyObject1, m_pMyObject2); | |
// m_pMyObject2 is dangling ptr. | |
} | |
void AMyActor::BeginPlay() | |
{ | |
Super::BeginPlay(); | |
UClass *pMyObjectClass = UMyObject::StaticClass(); | |
// case1 | |
{ | |
m_pMyObject1 = NewObject<UMyObject>(GetTransientPackage(), pMyObjectClass, TEXT("Obj1")); // property | |
m_pMyObject2 = NewObject<UMyObject>(GetTransientPackage(), pMyObjectClass, TEXT("Obj2")); // raw ptr | |
m_pMyObject1 = nullptr; | |
GetWorld()->ForceGarbageCollection(true); | |
// Obj1, Obj2 Destroy | |
} | |
// case2 | |
{ | |
m_pMyObject1 = NewObject<UMyObject>(GetTransientPackage(), pMyObjectClass, TEXT("Obj1")); // property | |
m_pMyObject2 = NewObject<UMyObject>(GetTransientPackage(), pMyObjectClass, TEXT("Obj2")); // raw ptr | |
GetWorld()->ForceGarbageCollection(true); | |
// Obj2 Destroy | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment