class FTestA { public: FTestA() { UE_LOG(LogTemp, Warning, TEXT("FTestA 构造")); } void TestFun() { UE_LOG(LogTemp, Warning, TEXT("FTestA TestFun方法")); } ~FTestA() { UE_LOG(LogTemp, Warning, TEXT("FTestA 析构")); } }; class FTestAChild : public FTestA { public: FTestAChild() { UE_LOG(LogTemp, Warning, TEXT("FTestAChild 构造")); } void TestFunChild() { UE_LOG(LogTemp, Warning, TEXT("FTestAChild TestFunChild方法")); } ~FTestAChild() { UE_LOG(LogTemp, Warning, TEXT("FTestAChild 析构")); } }; UFUNCTION(BlueprintCallable) void MyTest(); void AMyIntelligentPointer::MyTest() { //共享指针 { TSharedPtr<FTestA, ESPMode::NotThreadSafe> SharedPtr = MakeShareable(new FTestA); //创建时SharedReferenceCount=1 if (SharedPtr.IsValid()) { SharedPtr->TestFun(); int32 SharedReferenceCount = SharedPtr.GetSharedReferenceCount(); UE_LOG(LogTemp, Warning, TEXT("SharedReferenceCount : %d"), SharedReferenceCount); //手动释放 //SharedPtr = nullptr; UE_LOG(LogTemp, Warning, TEXT("SharedPtr.IsUnique : %d"), SharedPtr.IsUnique()); SharedPtr.Reset(); } } //共享引用 { //TSharedRef<FTestA, ESPMode::NotThreadSafe> SharedRef = MakeShareable(new FTestA()); //将共享指针隐式转换成引用 TSharedRef<FTestA, ESPMode::NotThreadSafe> SharedRef(new FTestA); SharedRef->TestFun(); int32 SharedReferenceCount = SharedRef.GetSharedReferenceCount(); UE_LOG(LogTemp, Warning, TEXT("SharedReferenceCount : %d"), SharedReferenceCount); UE_LOG(LogTemp, Warning, TEXT("SharedRef.IsUnique : %d"), SharedRef.IsUnique()); } //相互转化 { //共享引用转化成共享指针 UE_LOG(LogTemp, Warning, TEXT("共享引用转化成共享指针")); TSharedRef<FTestA, ESPMode::NotThreadSafe> SharedRef(new FTestA); TSharedPtr<FTestA, ESPMode::NotThreadSafe> SharedPtr = SharedRef; } { //共享指针转化成共享引用 UE_LOG(LogTemp, Warning, TEXT("共享指针转化成共享引用")); TSharedPtr<FTestA, ESPMode::NotThreadSafe> SharedPtr = MakeShareable(new FTestA); TSharedRef<FTestA, ESPMode::NotThreadSafe> SharedRef = SharedPtr.ToSharedRef(); } //继承关系转化 { TSharedPtr<FTestA, ESPMode::NotThreadSafe> SharedPtr = MakeShareable(new FTestAChild); if(SharedPtr.IsValid()) { SharedPtr->TestFun(); TSharedPtr<FTestAChild, ESPMode::NotThreadSafe> SharedPtr2 = StaticCastSharedPtr<FTestAChild>(SharedPtr); //ConstCastSharedPtr:常量共享指针转化 if (SharedPtr2.IsValid()) { SharedPtr2->TestFunChild(); } } } }
标签:FTestA,SharedPtr,LOG,TEXT,LogTemp,UE,共享,指针 From: https://www.cnblogs.com/wanhui/p/18063089