確認用のC++クラスを作成する
確認用のC++クラス「」を作成します。
C++クラスの作成手順
確認用のC++クラスを作成します。
C++ Classesの「LiteralAndConstants」フォルダから右クリック ->「New C++ Class」
「Actor」クラスを選択します。
「Actor」->「Next >」
クラス名を設定して、「Create Class」ボタンをクリックします。
Property | value |
---|---|
Class Type | Public |
Name | ConstinitActor |
Path | (末尾に)/LiteralAndConstants (分類分けして管理するため) |
constinit(C++20)
「constinit」はC++20で導入されたキーワードです。変数が静的に初期化されることを保証します。これにより、プログラムの起動時に変数が初期化されることを保証し、動的な初期化の遅延を防ぎます。「constinit」は、とくにグローバル変数や静的なメンバー変数に対して有用です。
「constint」はconst(定数式)またはLiteralを使用して初期化できます。
constexprと変数はconstinitを初期化に使用できません。
キーワード | constintとの組み合わせ |
---|---|
const | 〇 |
constexpr | ✕ |
Literal | 〇 |
variable | ✕ |
ConstinitActor.cpp
const int32 val1 {33};
constexpr int32 val2 {34};
int32 val3 {35};
constinit int32 age1 = 36;
const constinit int32 age2 {val1};
constinit int32 age3 {val2};
constinit int age4 {val3};
// Called when the game starts or when spawned
void AConstinitActor::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp, Display, TEXT("age1 : %d"), age1);
UE_LOG(LogTemp, Display, TEXT("age2 : %d"), age2);
UE_LOG(LogTemp, Display, TEXT("age3 : %d"), age3);
}
「constinit」に初期化で使用したconstexprと変数はエラーになります。
10>ConstinitActor.cpp(11): Error C2127 : 'age2': illegal initialization of 'constinit' entity with a non-constant expression
10>ConstinitActor.cpp(13): Error C2127 : 'age4': illegal initialization of 'constinit' entity with a non-constant expression
参照URL
ソースコード
ConstinitActor.cpp
ConstinitActor.cpp
// Copyright POSITA All Rights Reserved.
#include "LiteralAndConstants/ConstinitActor.h"
const int32 val1 {33};
constexpr int32 val2 {34};
int32 val3 {35};
constinit int32 age1 = 36;
// const constinit int32 age2 {val1}; // error
constinit int32 age3 {val2};
// constinit int age4 {val3}; // error
// Sets default values
AConstinitActor::AConstinitActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AConstinitActor::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp, Display, TEXT("age1 : %d"), age1);
// UE_LOG(LogTemp, Display, TEXT("age2 : %d"), age2);
UE_LOG(LogTemp, Display, TEXT("age3 : %d"), age3);
// UE_LOG(LogTemp, Display, TEXT("age4 : %d"), age4);
}
// Called every frame
void AConstinitActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}