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

相关推荐
zhanghaha131421 分钟前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
白狐_79835 分钟前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander2581 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
知识分享小能手1 小时前
线性代数学习教程,从入门到精通,向量组的线性相关性 — 完整知识点梳理(7)
学习·线性代数·机器学习
Shell运维手记1 小时前
Linux 常用基础命令学习笔记
linux·运维·笔记·学习·算法·github
qq_448011161 小时前
C语言中的动态内存分配
c语言·开发语言·php
船厂电气自动化ai大模型2 小时前
AI大模型与数学 第32课 函数凹凸性与二阶导数:拐点求解、凹凸区间计算(10道二阶导数计算题)
数据结构·人工智能·python·深度学习·算法
动词ing2 小时前
【学习笔记】C语言(数组指针与指针数组+字符数组+函数+参数传递+字符串作为形参+递归函数+指针函数+回调函数+结构体嵌套+内存动态分配函数)
c语言·笔记·学习
旖旎夜光2 小时前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
汉字萌萌哒2 小时前
2024CSP-J入门级C++真题详解
开发语言·c++