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

相关推荐
WJ.Polar15 小时前
Java封装、继承、多态
java·开发语言
摇滚侠15 小时前
Java 中如何表示负数,有符号和无符号的区别,补码的计算规则,char byte short int long 的范围
java·开发语言
weixin_3077791315 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
xier_ran15 小时前
【infra之路】AI 编译器学习笔记(十三):AI 编译器全景——TVM、XLA、IREE 与其他
人工智能·笔记·学习
连山齐名15 小时前
ai应用开发的学习笔记
服务器·笔记·学习
爱读书的小胖16 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
鸽鸽程序猿16 小时前
【项目】【在线判题系统】b端题目增删改
开发语言·python
by2099916 小时前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表
Lhappy嘻嘻16 小时前
读懂 JVM:内存模型、类加载机制、分代回收
java·开发语言·jvm
xier_ran16 小时前
【infra之路】AI 编译器学习笔记(十四):为什么要 tiling,以及矩阵计算单元的“固定“
人工智能·笔记·学习