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

标签 c++ c++11 initialization value-initialization copy-initialization

我已经阅读了很多 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 {}; 执行 value initialization带有自 C++11 起支持的大括号初始化器作为效果,

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.

关于c++ - 在 C++ 中初始化变量的 = 和 {} 语法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405190/

相关文章:

c++ - 如何在 C++11 中检测一个类是否是最终的?

c++ - std::underlying_type :SFINAE 是否可以防止未定义的行为?

c - LL 中的初始化函数

java - 任何方法之外的 {} 的用途是什么?

c++ - 使用 SHGetPathFromIDList 将 PIDL 转换为文件路径

c++ - 使用 openCV 创建 super 矩阵

c++ - 如何在 C++ 中初始化结构数组?

c++ - Boost d_ary_heap/priority_queue 编译错误: deleted function

python - super() 和父类名有什么区别?

c++ - "ALWAYS use a named regex, NEVER a temporary"- 为什么?