难以理解的POD默认初始化

Incomprehensible default initialization of POD

我在这里和 cppreference 中读了很多,自动 POD 类型不是默认初始化的,但我尝试测试一些代码,但我得到了一些奇怪的结果。看:

#include <iostream>

int main( ) {
    int x;
    std::cout << "x: " << x << std::endl;
    return 0;
}

它将输出x一些随机值。但是如果我这样修改我的代码:

#include <iostream>

void f( ) { 
    int i;
    std::cout << "i: " << i << std::endl;
}

int main( ) {
    f( );
    int x;
    std::cout << "x: " << x << std::endl;   
    return 0;
}

我将得到以下输出:

i: 0
x: 4200814

如果我在声明 x 及其输出之后修改函数调用 f( ); 的顺序,xi 将设置为随机值。另一件事:如果我在声明 x 及其输出之后声明另一个没有初始化的变量,比如 int y;,y 也会输出 0。

那么,为什么那个变量 i 以及可能在函数 f 中声明的所有其他变量都是 'initializated' 到 0。也许未定义行为或不确定值的结果?

I read a lot here and in cppreference that automatic POD types isn't default initializated,

这是不正确的。当一个对象没有显式初始化时,它是默认初始化的。默认初始化的含义因类型而异。

来自 C++11 标准:

8.5 Initializers

...

6 To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

— otherwise, no initialization is performed.

因此xi没有初始化。


Maybe a consequence of underfined behavior or indeterminate value?

是的。使用未初始化变量的值会导致未定义的行为。

ix 的值可以是任何值。不要指望任何特定的模式。 当您重新编译时,它们的值很可能会改变,当您更改编译器选项时,更改编译器。