C++中指定初始值设定项的未定义行为
在我尝试过的所有编译中,没有任何警告地接受以下 C++20 程序:
struct A { const int & x = z; int y = x; int z; };
int main()
{
return A{.z=3}.y;
}
https://gcc.godbolt.org/z/nqb95zb7c
但是每个程序都会返回一些任意值。假设这是未定义的行为是否正确?
回答
成员按照它们在类定义中出现的顺序进行初始化,因此指定的初始化器不是那么相关,而且这个
struct A {
const int & x = z;
int y = x; // <- read of indeterminate value !
int z = 42; // <- doesn't really matter because y is initialized before !
};
int main() {
return A{}.y;
}
出于同样的原因未定义。
另请参阅cppreference 中的示例:
struct A { string str; int n = 42; int m = -1; }; A{.m=21} // Initializes str with {}, which calls the default constructor // then initializes n with = 42 // then initializes m with = 21
这个例子实际上是为了说明别的东西,但它也展示了成员是如何按顺序初始化的。