UE中使用TGuardValue与TInlineComponentArray数据结构

UE中有2种比较有趣的数据结构TGuardValue与TInlineComponentArray,TGuardValue可以让变量离开作用域时恢复原始值,而在作用域中可以任意修改。TInlineComponentArray可以在栈中更高效的分配数组(因为TArray存在一些非栈的额外分配)。

1.TGuardValue

以下为测试代码:

cpp 复制代码
UE_LOG(LogTemplateCharacter, Warning, TEXT("========== TGuardValue Demo =========="));

int32 Value = 100;
UE_LOG(LogTemplateCharacter, Warning, TEXT("[TGuardValue] Before scope: Value = %d"), Value);
//打印Value = 100
{
	// 一般修改值在构造函数里直接设置
	TGuardValue<int32> Guard(Value, 999);
	UE_LOG(LogTemplateCharacter, Warning, TEXT("[TGuardValue] Inside scope:  Value = %d (temporarily overridden)"), Value);

	Value = 42;//即使被 TGuardValue '保护',变量依然可以被随意修改,Guard 只负责在最后复原,不负责阻止修改。
	UE_LOG(LogTemplateCharacter, Warning, TEXT("[TGuardValue] Inside scope:  Value = %d (modified again while guarded)"), Value);
} // 在C++里,花括号可以算作作用域,出了作用域值恢复

UE_LOG(LogTemplateCharacter, Warning, TEXT("[TGuardValue] After scope:  Value = %d (restored to original)"), Value);
//打印Value = 100

可以发现,出了花括号作用域数值恢复,运行时截图测试:

在UE的Lyra项目中,也使用到了该数据结构。

2.TInlineComponentArray

我们知道C++如果不声明为指针,默认是在栈上分配的。但因为TArray本身构造函数中存在一些非栈的初始化逻辑代码,因此对于需要在栈上分配的数组使用TInlineComponentArray效率会更高。

测试代码,使用指针遍历成员:

cpp 复制代码
TInlineComponentArray<UActorComponent*> InlineComponents(this);

UE_LOG(LogTemplateCharacter, Warning,
	TEXT("[TInlineComponentArray] Collected %d components from '%s' (inline capacity default = %d)"),
	InlineComponents.Num(),
	*GetName(),
	NumInlinedActorComponents);

for (int32 Index = 0; Index < InlineComponents.Num(); ++Index)
{
	UActorComponent* Component = InlineComponents[Index];
	UE_LOG(LogTemplateCharacter, Warning,
		TEXT("[TInlineComponentArray]   [%d] %s (%s)"),
		Index,
		*GetNameSafe(Component),
		Component ? *Component->GetClass()->GetName() : TEXT("null"));
}

运行时测试下:


https://dev.epicgames.com/documentation/unreal-engine/API/Runtime/Core/TGuardValue

https://dev.epicgames.com/documentation/unreal-engine/API/Runtime/Engine/TInlineComponentArray

相关推荐
传奇开心果编程8 分钟前
【Rust入门知识点学与练】第3课:String 与 &str 的区别
开发语言·学习·rust
秋名RG19 分钟前
Java 核心特性一览
java·开发语言
平头哥AI1 小时前
Day 01 | go run 跑通第一个 Go 程序,go build 留下一个能拷走的 exe
开发语言·后端·golang
小雨笙笙1 小时前
机器学习:线性回归学习
学习·机器学习·线性回归
HugoStudio_SWAN1 小时前
洛谷 P1420 / P1179 / B4262 最长连号、数字统计与词频统计——统计的三种面孔
c++·学习·程序人生·算法
葡萄城技术团队1 小时前
工业数据可视化:使用活字格 AIcoding + Three.js 构建轻量化三维设备监控大屏
开发语言·javascript·信息可视化
qiaosaifei1 小时前
JAVA老项目中有大量的类名_编译时报找不到符号错误
java·开发语言
聪明蛋子哟2 小时前
MCP协议深度落地:如何用Python/Java双语言实现统一的工具调用网关?
java·开发语言·python
是隼人2 小时前
buuctf-pwn [HarekazeCTF2019]baby_rop2(64位ret2libc)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
一晌小贪欢2 小时前
python-第27天:Python面向对象详解
开发语言·python·数据可视化·面向对象·python办公