未初始化的 C++ 结构的行为

Behaviour of uninitialized C++ structs

假设我们在局部范围内声明了一个结构数组:

    int main()
{
    RandomStruct array [1000];
}

当前数组中的结构未初始化。虽然这意味着结构变量也未初始化,但这还意味着什么吗?例如,如果我将未初始化结构中的所有变量设置为所需值,然后使用该结构的函数,或者如果我使用在设置之前不使用未初始化变量的结构函数。我是否正确地认为只有变量将未初始化,而数组所做的只是为结构的每个变量分配随机内存?

Currently the structs in the array are uninitialized

不,他们是 default-initialized

While this means that the struct variables are also uninitialized

对成员的影响取决于RandomStruct的定义。根据该定义,RandomStruct 的默认初始化可能 具有 RandomStruct 的部分或全部非静态数据成员的默认初始化效果。它可能最终会默认初始化非class类型的变量,作为RandomStruct的成员或成员的成员等. 非 class 类型的变量将具有不确定的值。

Like if I, for example, set all the variables from an unitialized struct to the desired value, and then use functions of this struct, or if I use functions of the struct that don't use uninitialized variables before I set them

如果所有成员在使用前都初始化为确定值,则一切正常。不“观察”不确定值的成员函数调用是可以的。

Am I correct in thinking that only the variables will be uninitialized and that what the array does is just assign random memory to each of the struct's variables?

这不完全正确。这意味着观察不确定值是可以的,但它们的值是未知的。它不是。但只要您不观察这些值,这就是一个有效的直觉。

只要不被观察到,就可以让它们不确定。但是,它是 未定义的行为 "observe" the indeterminate value 通过在任何评估中产生它,除非在非常有限的枚举条件下。

这意味着不允许正确的程序观察该值,但也不需要编译器对其进行诊断。但是,编译器可以假设它永远不会完成(因为正确的程序无法完成)并且 C++ 对无效程序没有任何要求。