在 C++ 中初始化变量的 = 和 {} 语法之间的区别

Difference between = and {} syntaxes for initializing a variable in C++

我读过不少C++代码,遇到过两种初始化变量的方法。

方法一:

int score = 0;

方法二:

int score {};

我知道 int score {}; 会将分数初始化为 0,int score = 0;

也是如此

这两者有什么区别?我已阅读 initialization: parenthesis vs. equals sign 但这并没有回答我的问题。我想知道 等号 花括号 之间的区别是什么,而不是圆括号。在什么情况下应该使用哪一个?

int score = 0;执行copy initialization,效果为score初始化为指定值0.

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T.

int score {}; 使用自 C++11 起支持的花括号初始化器执行 value initialization 作为效果,

otherwise, the object is zero-initialized.

score是内置类型int,最后是zero-initialized,即初始化为0.

If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.

您可能对 ISO/IEC 14882 8.5.1 感兴趣。它会告诉你 brace-or-equal-initializer 可以是 assignment-expressionbraced-init-list。 在方法 2 中,您在标量类型上使用默认初始化程序, 应设置为零。