3.2 KiB
Raw Blame History

Const

  • 功能描述: 指定该函数参数不可更改
  • 元数据类型: bool
  • 引擎模块: Blueprint, Parameter
  • 作用机制: 在PropertyFlags中加入CPF_ConstParm在Meta中加入NativeConst
  • 常用程度:

指定该函数参数不可更改。

如果在C++代码的参数上直接加const则会自动的被UHT识别并添加CPF_ConstParm 标志以及NativeConst元数据。但也可以手动加上UPARAM(const)来强制UHT添加CPF_ConstParm效果见下面蓝图中的Out节点把输出参数变成了输入参数。

虽然不知道什么情况下需要手动添加因此在源码中没有找到实际的用例。能想到的用处是在蓝图层面使它变成const输入参数但是在C++层面依然是可变的引用参数方便在C++里调用一些非const的方法。

测试代码:

//PropertyFlags:	CPF_ConstParm | CPF_Parm | CPF_ZeroConstructor | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_ConstInt(UPARAM(const) int value);

	//PropertyFlags:	CPF_ConstParm | CPF_Parm | CPF_OutParm | CPF_ZeroConstructor | CPF_ReferenceParm | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_ConstIntOut(UPARAM(const) int& value);

	//(NativeConst = )
	//PropertyFlags:	CPF_ConstParm | CPF_Parm | CPF_OutParm | CPF_ZeroConstructor | CPF_ReferenceParm | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_ConstIntRef(UPARAM(const) const int& value);

	//PropertyFlags:	CPF_Parm | CPF_ZeroConstructor | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_NoConstInt(int value);

	//PropertyFlags:	CPF_Parm | CPF_OutParm | CPF_ZeroConstructor | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_NoConstIntOut(int& value);

	//(NativeConst = )
	//PropertyFlags:	CPF_ConstParm | CPF_Parm | CPF_OutParm | CPF_ZeroConstructor | CPF_ReferenceParm | CPF_IsPlainOldData | CPF_NoDestructor | CPF_HasGetValueTypeHash | CPF_NativeAccessSpecifierPublic 
	UFUNCTION(BlueprintCallable)
	FString MyFuncTestParam_NoConstIntRef(const int& value);

蓝图节点:

MyFuncTestParam_ConstIntOut的输出Value变成了输入的Value因为不能改变。

Untitled

原理代码:

在代码中实际出现const就会增加CPF_ConstParam Flag。

\Engine\Source\Programs\Shared\EpicGames.UHT\Parsers\UhtPropertyParser.cs 1030

if (propertySettings.PropertyCategory != UhtPropertyCategory.Member && !isTemplateArgument)
{
	// const before the variable type support (only for params)
	if (tokenReader.TryOptional("const"))
	{
		propertySettings.PropertyFlags |= EPropertyFlags.ConstParm;
		propertySettings.MetaData.Add(UhtNames.NativeConst, "");
	}
}