当前位置:网站首页>UE4 smart pointer and weak pointer
UE4 smart pointer and weak pointer
2022-07-26 14:11:00 【Flying Pig】
One 、 preface
We know C++ It has its own pointer , But in the unreal engine, native C++ The pointer of will cause some problems when allocating and freeing memory , For example, it cannot be recycled by illusion , Cause problems such as memory leakage , So the illusion gave rise to the intelligent pointer . Unreal smart pointer Library yes C++11 Custom implementation of smart pointer , Designed to reduce the burden of memory allocation and tracking . This implementation includes industry standards Share pointer 、 Weak pointer and The only pointer . It also adds something like a non nullable shared pointer Shared reference . These classes cannot be associated with UObject Use the system together , Because phantom objects use a separate memory tracking system , The system makes better adjustments for the game code .
Two 、 The meaning of each pointer
Share pointer (TSharedPrt): The shared pointer owns the object it refers to , Prevent deleting the object indefinitely , And eventually there are no shared pointers or shared references , Handle its deletion when referencing it . The shared pointer can be null , This means that it does not reference any objects . Any non null shared pointer can generate a shared reference to the object it references .
Shared reference (TSharedRef): Shared references work like shared pointers , Because it has the object it refers to . They differ in terms of empty objects ; Shared references must always reference non empty objects . Because shared pointers don't have this limitation , So shared references can always be converted to shared pointers , And the shared pointer ensures that a valid object is referenced . When you want to ensure that the referenced object is not empty , Or if you want to indicate ownership of shared objects , Please use shared references .
Weak pointer (TWeakPtr): Weak pointers are similar to shared pointers , But do not own the objects they reference , Therefore, it will not affect its life cycle . This property is very useful , Because it breaks the reference loop , But it also means that the weak pointer can become null at any time , Instead of warning . For this reason , A weak pointer can generate a shared pointer to the object it refers to , This ensures that programmers can access the object temporarily and safely .
The only pointer (TUniquePtr): A unique pointer individually and explicitly owns the object it refers to . Because a given resource can only have one unique pointer , So the only pointer can transfer ownership , But you can't share it . Any attempt to copy a unique pointer will result in compilation errors . When the unique pointer is out of range , It will automatically delete the object it refers to .
3、 ... and 、 How to use the pointer
In order to better use pointers , Unreal provides several help classes and functions , Make it easier to use smart pointers 、 More intuitive .
| from |
| From the routine C++ Pointer create shared pointer . |
| Static conversion utility function , Usually used to convert down to a derived type . |
| take |
Four 、 Advantages and disadvantages of using smart pointers
advantage :
std::Shared_Ptr Not available on all platforms .
Make it more consistent on all compilers and platforms .
It can work seamlessly with other virtual containers .
Better control platform features , Including threading and optimization .
Thread safe functions .
We want more control over performance ( The function of convergence , Memory , Virtual function, etc ).
There is no need to introduce third-party dependencies when they are not needed .
shortcoming :
Creating and copying smart pointers is better than creating and copying original C++ Pointers involve more overhead .
Maintaining the reference count increases the cycle of basic operations .
Some smart pointers are better than the original C++ Pointers use more memory .
The reference controller has two heap allocations . Use
MakeSharedinstead ofMakeShareableAvoid second allocation , And it can improve performance .
5、 ... and 、 Case test
Native C++ And smart pointer
Create a C++ Actor class Name it MyActor
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"
class TaskA
{
public:
int32 a;
float b;
};// Create a native C++ class
UCLASS()
class HEXINU4_API AMyActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMyActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void TaskAA();// Shared pointer test function
void TaskSharedRef();// Shared reference test function
void TaskSharedRefAndPtr();// Shared pointers and shared references are mutually transformed
void TaskweakPrt();// Weak pointer test function
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
TSharedPtr<TaskA> Task_a;// The shared pointer can be NULL But you can't copy , Use shared pointers, preferably global pointers , Don't create temporary pointers. It consumes more resources than ordinary pointers
};
// TSharedRef<TaskA> Task_b;// It is wrong not to declare a shared reference like this
TWeakPrt<TaskA> Task_c;// Declaration of weak pointers
void AMyActor::TaskAA()
{
Task_a= MakeShareable(new TaskA());// Sharing pointers creates a smart pointer
if (Task_a.IsValid() || Task_a.Get())// Determine whether the shared pointer is valid or dereferenced
{
Task_a.Get()->a;// Can be replaced by Task_a->a;
Task_a.Reset();
}
}
void AMyActor::TaskSharedRef()
{
TSharedRef<TaskA> Task_b(new TaskA());// Shared references must initialize available objects
Task_b->a;
}
void AMyActor::TaskSharedRefAndPtr()
{
// Convert shared references to shared pointers
TSharedRef<TaskA> Task_b(new TaskA());
Task_a = Task_b;
// Convert ordinary pointer to shared pointer
TaskA *NewTaskA = new TaskA();
Task_a = MakeShareable(new NewTaskA);
// Be careful
// Task_b = nullptr;// FALSE
Task_b = Task_a.ToSharedRef();// It is unsafe to convert a shared pointer into a shared reference. It has an assertion
}
void AMyActor::TaskweakPrt()
{
TSharedPtr<TaskA> _TaskA_ptr = MakeShareable(new TaskA());// Share pointer
TSharedRef<TaskA> _TaskA_ref(new TaskA());// Shared reference
TweakPtr<TaskA>Task_D(_TaskA_ptr);
TweakPtr<TaskA>Task_K(_TaskA_ref);
Task_c = Task_D;
Task_c = Task_K;
Task_c = nullptr;// Prevent objects from being destroyed
// Weak pointer into smart pointer
TSharedPtr<TaskA> NewTask(Task_c.Pin());
if(NewTask.IsValid())
{
NewTask->a;
}
}Conversion between smart pointers
class FBase
{
public:
protected:
private:
};
class FB : public FBase
{
public:
void Printf() {};
protected:
private:
};
// Convert the base class into a derived class , Access functions and variables of derived classes
TSharedPtr<FBase> B_ = MakeShareable(new FB());// Share pointers and UObject Are not compatible ,UObject It has its own destruction mechanism
TSharedPtr<FB> C_ = StaticCastSharedPtr<FB>(B_);
if (C_.IsValid())
{
C_->Printf();
}
const TSharedPtr<FBase> E_ = MakeShareable(new FB());
TSharedPtr<FBase> D_ = ConstCastSharedPtr<FBase>(E_);
TSharedPtr<FB> F_ = StaticCastSharedPtr<FB>(D_);
if (F_.IsValid())
{
F_->Printf();
}TSharedFromThis() Usage of : Keep a weak reference to the object , It is convenient to convert directly into shared references AsShared();
class TaskA:public TSharedFromThis<TaskA>
{
public:
int32 a;
float b;
};
.CPP Test in file
TSharedPtr<TaskA>NewTest = MakeShareable(new TaskA());
newtask->a;
TaskA *NewTest1 = NewTest.Get();// Dereference converts smart pointers into native pointers
if (NewTest1)
{
NewTest1->AsShared();
}
TaskA *currentTask = new TaskA();// Native pointers
TSharedRef<TaskA> Task_c = currentTask->AsShared();Comprehensive case
#include "CoreMinimal.h"//
class IMyID// A user ID class
{
public:
IMyID()
{
ID = FMath::RandRange(100, 1000);
}
FORCEINLINE uint64 GetID() { return ID; }// Forced introversion ID
private:
int32 ID;
};
class FData:public IMyID// Data inheritance ID class , Have your own data parameters
{
public:
FData()
{
Health = 100.f;
bDeath = 0;
PlayerName = TEXT("CharacterOne");
}
float Health;
uint8 bDeath;
FName PlayerName;
};
class FDataManager// Data management class
{
public:
static TSharedRef<FDataManager> Get()
{
if (DataMager.IsValid())
{
DataMager = MakeShareable(new FDataManager());
}
return DataMager.ToSharedRef();
}
TSharedRef<FData> CreatData()
{
TSharedPtr<FData> tmp_Data = MakeShareable(new FData());
MyData.Add(tmp_Data->GetID(), tmp_Data);
return tmp_Data.ToSharedRef();
}
~FDataManager()
{
}
private:
static TSharedPtr<FDataManager> DataMager;
TMap<uint64, TSharedPtr<FData>> MyData;
};
// The role instance displays
class FCharacter
{
public:
FORCEINLINE bool IsValid()
{
return NewData.IsValid();
}
void SetNewData(TSharedRef<FData> CurrentNewData) { NewData = CurrentNewData; }
void SetNewName( FString NewName)
{
if (NewData.IsValid())
{
NewData.Pin()->PlayerName = FName(*NewName);
}
}
FORCEINLINE bool IsValid() { return NewData.IsValid(); }
protected:
private:
TWeakPtr<FData> NewData;// Weak pointers do not participate in the life cycle of classes
};
void NewMain()// Suppose it is a scenario
{
FCharacter* Character = new FCharacter();
Character->SetNewData(FDataManager::Get()->CreatData());
Character->SetNewName("PlayerTwo");
}
// Note that if it is a bare pointer (C++ Native pointers ) When you delete this pointer, it will crash , Generate field pointer , The solution is to add a TSharedFromThis(FData), Let it always be wrapped by a weak pointer
class FData:public IMyID,public TSharedFromThis(FData)// Data inheritance ID class , Have your own data parameters
{
public:
FData()
{
Health = 100.f;
bDeath = 0;
PlayerName = TEXT("CharacterOne");
}
float Health;
uint8 bDeath;
FName PlayerName;
};
FData* CreatData()
{
TSharedPtr<FData> tmp_Data = MakeShareable(new FData());
MyData.Add(tmp_Data->GetID(), tmp_Data);
return tmp_Data.Get();
}
void NewMain()// Suppose it is a scenario
{
FCharacter* Character = new FCharacter();
FData* New_Data = FDataManager::Get()->CreatData();
Character->SetNewData(New_Data->AsShared());
Character->SetNewName("PlayerTwo");
}
边栏推荐
- Flink SQL (III) connects to the external system system and JDBC
- 基于SPO语义三元组的疾病知识发现
- C语言_结构体指针来访问结构体数组
- JS submit the form to determine whether the user name and password are empty
- Job 7.25 sorting and searching
- C语言_结构体指针变量引入
- Redis learning notes
- Solve the problem that JUnit of idea console cannot be input with scanner
- How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects
- 多态案例-制作饮品
猜你喜欢

Pytoch learning notes (I) installation and use of common functions

Construction practice of pipeline engine of engineering efficiency ci/cd

循环队列(c语言实现)

Large and small end mode

How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects

First knowledge of opencv4.x --- image perspective transformation

GDB common commands

聚力打造四个“高地”,携手合作伙伴共铸国云!
![[GYCTF2020]FlaskApp](/img/ee/dcb42617af4a0e41657f6cf7095feb.png)
[GYCTF2020]FlaskApp

大小端模式
随机推荐
『SignalR』.NET使用 SignalR 进行实时通信初体验
Native JS get transform value x y z and rotate rotation angle
Book download | introduction to lifelong supervised learning in 2022, CO authored by meta AI, CMU and other scholars, 171 Pages pdf
@千行百业,一起乘云而上!
Plato Farm有望通过Elephant Swap,进一步向外拓展生态
First knowledge of opencv4.x --- image perspective transformation
@A thousand lines of work, ride the cloud together!
作业7.25 排序与查找
循环队列(c语言实现)
mysql5.7通过文件zip方式安装-九五小庞
[deep learning] fully connected network
Mobile dual finger scaling event (native), e.originalevent.touches
C language_ Structure pointer to access structure array
[paper reading] raw+:a two view graph propagation method with word coupling for readability assessment
Digital collections accelerate the breaking of the circle and help the industry find new opportunities
Mlx90640 infrared thermal imager temperature sensor module development notes (6)
『BaGet』带你一分钟搭建自己的私有NuGet服务器
Technology sharing | gtid that needs to be configured carefully_ mode
GDB common commands
Research on Chinese medicine assisted diagnosis and treatment scheme integrating multiple natural language processing tasks -- taking diabetes as an example