C++14 值初始化问题

c++14 value initialization issue

谁知道本地 i_local 值在此示例中被零初始化 http://ideone.com/Cqer9Z

#include <iostream>
using namespace std;

int main() {

    int i_local; // automatic storage duration, not static

    cout << "Value of i_local: " << i_local << endl; // (2-3) value is undetermined
}

它是可变的,自动存储持续时间,根据标准应该有未确定的值。

在我的本地计算机 (c++11) 中未确定,但在 ideone (c++14) 中归零。

零是 int 的值之一,因此将 int 未确定的值设为零是完全合法的。

此外,即使尝试读取该整数也是 UB,因此根据定义,您看到的值毫无意义。

完整的标准说(强调):

When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.18). [...] If an indeterminate value is produced by an evaluation, the behavior is undefined except [in some irrelevant cases...]

您有未定义的行为。它可以打印 0,它可以打印 50,它可以打印乱码,或者它可以擦除你的硬盘。