变量初始化,有什么区别?

Variable initialization, what's the difference?

在我的 header 中,我有这两个 public 变量:

float testVariable1 = 1.23456789f;
float testVariable2{ 1.23456789f };

这里有什么区别? 为什么有带大括号的版本?

他们对这个案例有同样的效果。

第一个是copy initialization

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.

第二个是direct-list-initialization

Otherwise (if T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type whose referenced type is same as or is a base class of the type of the element, T is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.

Otherwise, standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T, and the initial value of the object being initialized is the (possibly converted) value.

作为内置类型,潜在的区别之一是 list initialization 中不允许缩小转换。 (即使在这种情况下也不会应用它,因为初始化程序已指定为 float 文字。)

C++ 支持三种初始化变量的基本方法。 首先,我们可以使用等号进行复制初始化:

int width = 5; // copy initialization of value 5 into variable width

这会将 equals 右侧的值复制到左侧创建的变量。 其次,我们可以使用括号直接初始化。

int width( 5 ); // direct initialization of value 5 into variable width

对于简单数据类型(如整数),复制和直接初始化本质上是相同的。但对于一些高级类型,直接初始化可以比复制初始化执行得更好。 在 C++11 之前,由于性能提升,在大多数情况下建议直接初始化而不是复制初始化。

不幸的是,直接初始化不能用于所有类型的初始化。为了提供更一致的初始化机制,C++11 添加了一种用于直接初始化的新语法,称为大括号初始化(也称为统一初始化),它使用大括号:

int width{ 5 }; // brace (uniform) initialization of value 5 into variable width

希望对您有所帮助。