参考:https://docs.unrealengine.com/4.27/zh-CN/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/SmartPointerLibrary/WeakPointer/
定义
弱指针 存储对象的弱引用。与 共享指针 或 共享引用 不同,弱指针不会阻止其引用的对象被销毁。
作用
弱指针的使用有助于授予意图——弱指针表明对引用对象的观察,而无需所有权,同时不控制其生命周期。
应用:打破引用循环
两个或多个对象使用智能指针保持彼此间的强引用时,将出现引用循环。在此类情况下,对象间会相互保护以免被删除。各对象固定被另一对象引用,因此对象无法在另一对象存在时被删除。如外部对象未对引用循环中对象进行引用,其实际上将出现泄漏。弱指针不会保留自身引用的对象,因此其可中断此类引用循环。要在未拥有对象时对其进行引用,并延长其寿命时,可使用软指针。
演示代码
演示斗兽棋鼠、象、狮子的相互克制关系,注意只需把一个成员的指针类型改成弱指针,就可以打破引用循环。
头文件:
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"#include "UObject/NoExportTypes.h"#include "testWeakptrO.generated.h"/****/UCLASS(Blueprintable)class TESTCPP_API UtestWeakptrO : public UObject{GENERATED_BODY()public:UFUNCTION(BlueprintCallable)void testWeakptr();};class IAnimal {public:virtual void SetRestraint(const TSharedPtr<IAnimal> &InWhatAnimal) = 0;virtual ~IAnimal(){}};class Fmouse :public IAnimal {public://只需把一个成员的指针类型改成弱指针,就可以中断引用循环//TSharedPtr<Fmouse> elephant;TWeakPtr<Fmouse> elephant;Fmouse() { UE_LOG(LogTemp, Warning, TEXT("mouse atk elephant")); }virtual void SetRestraint(const TSharedPtr<IAnimal>& InWhatAnimal) { elephant = StaticCastSharedPtr<Fmouse>(InWhatAnimal); }virtual ~Fmouse() { UE_LOG(LogTemp, Warning, TEXT("mouse is dead")); }};class Flion :public IAnimal {public:TSharedPtr<Flion> mouse;Flion() { UE_LOG(LogTemp, Warning, TEXT("lion atk mouse")); }virtual void SetRestraint(const TSharedPtr<IAnimal>& InWhatAnimal) { mouse = StaticCastSharedPtr<Flion>(InWhatAnimal); }virtual ~Flion() { UE_LOG(LogTemp, Warning, TEXT("lion is dead")); }};class Felepant:public IAnimal{public:TSharedPtr<Felepant> lion;Felepant(){UE_LOG(LogTemp, Warning, TEXT("elephant atk lion")); }virtual void SetRestraint(const TSharedPtr<IAnimal>& InWhatAnimal) { lion = StaticCastSharedPtr<Felepant>(InWhatAnimal); }virtual ~Felepant(){ UE_LOG(LogTemp, Warning, TEXT("elephant is dead")); }};
实现:
// Fill out your copyright notice in the Description page of Project Settings.#include "testWeakptrO.h"void UtestWeakptrO::testWeakptr(){ //构造3个动物类的ptr对象TSharedPtr<Felepant> myobjEle = MakeShareable(new Felepant);//ptrNum count+1TSharedPtr<Fmouse>myobjMou = MakeShareable(new Fmouse);//ptrNum count+1TSharedPtr<Flion>myobjFli = MakeShareable(new Flion);//ptrNum count+1//获取计数int32 EleCount = myobjEle.GetSharedReferenceCount();int32 MouCount = myobjMou.GetSharedReferenceCount();int32 FliCount = myobjFli.GetSharedReferenceCount();UE_LOG(LogTemp, Warning, TEXT("GetSharedReferenceCount:ElephantCount=%d\n LionCount=%d\n MouseCount=%d\n"),EleCount,MouCount,FliCount);}

