当前位置:网站首页>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");
}
边栏推荐
- 基于SPO语义三元组的疾病知识发现
- Propagation of transactions
- MySQL's practice of SQL analysis and optimization from the index principle
- Inspiration from brain: introduction to synaptic integration principle in deep neural network optimization
- Mobile dual finger scaling event (native), e.originalevent.touches
- JS get the current time, time and timestamp conversion
- .net6与英雄联盟邂逅之——根据官方LCU API制作游戏助手
- 融合多自然语言处理任务的中医辅助诊疗方案研究——以糖尿病为例
- 404 pages and routing hooks
- JS page turning, kkpager.js page turning
猜你喜欢

Mlx90640 infrared thermal imager temperature sensor module development notes (6)

Videojs to canvas pause, play, switch video

在检测分割中一些轻量级网络模型(自己学习的笔记分享)

Docker container MySQL enables binlog and scheduled backup

Plato farm is expected to further expand its ecosystem through elephant swap

IDEA(warning)No artifacts configured

Add a display horizontal line between idea methods

【论文阅读】GRAW+:A Two-View Graph Propagation Method With Word Coupling for Readability Assessment

天翼云Web应用防火墙(边缘云版)支持检测和拦截Apache Spark shell命令注入漏洞

Sequence traversal of binary tree (implemented in C language)
随机推荐
JS timer realizes the countdown and jumps to the login page
【数学建模】常用基本模型总结
POM file details
[paper reading] raw+:a two view graph propagation method with word coupling for readability assessment
Research on technology subject division method based on patent multi-attribute fusion
基址寻址和变址寻址区别
~6. CCF 2021-09-1 array derivation
『云原生』KubeSphere可插拔组件之DevOps系统
gdb常用命令
Multi task text classification model based on tag embedded attention mechanism
"Intermediate and advanced test questions": what is the implementation principle of mvcc?
How to quickly design a set of cross end components that support rendering rich text content
The picture moves horizontally with the phone - gyroscope. 360 degree setting conditions
Segmentation fault (core dumped)
Detailed explanation of alter field of MySQL Foundation
敏捷开发与DevOps的对比
JS submit the form to determine whether the user name and password are empty
Tianyi cloud web application firewall (edge cloud version) supports the detection and interception of Apache spark shell command injection vulnerabilities
万字长文,浅谈企业数字化建模蓝图
手持振弦采集仪VH03各种接口使用说明