[英]Strange initialization in C++11
I've heard I can initialize a value using this syntax: 我听说我可以使用以下语法初始化值:
int foo = {5};
Also, I can do the same thing using even less code: 另外,我可以使用更少的代码来做同样的事情:
int foo{5};
Well, are there any advantages/disadvantages of using them? 那么,使用它们有什么优点/缺点吗? Is it a good practice, or maybe it's better to use standard: ?
这是一个好习惯,还是最好使用standard :?
int foo = 5;
The three examples you gave, are not quite the same. 您提供的三个示例并不完全相同。 Uniform initialization (the ones with
{ }
) does not allow narrowing conversions 统一初始化(带有
{ }
初始化)不允许缩小转换范围
int i = 5.0; // Fine, stores 5
int i{5.0}; // Won't compile!
int i = {5.0}; // Won't compile!
Furthermore, copy initializations (the ones with an =
) do not allow explicit constructors. 此外,复制初始化(带有
=
初始化)不允许使用显式构造函数。
The new C++11 feature uniform initialization and its cousin initializer-lists (which generalizes the brace initialization syntax to eg the standard containers) is a tricky animal with many quirks. 新的C ++ 11具有统一的初始化功能及其表亲初始化列表(将括号初始化语法推广到例如标准容器中)是一个棘手的动物,具有许多怪癖。 The most vexing parse mentioned in the comments by @Praetorian is only one of them, tuples and multidimensional arrays are another pandora's box.
@Praetorian评论中提到的最令人烦恼的解析只是其中之一,元组和多维数组是另一个潘多拉盒子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.