C++0x 广义初始值设定项的非歧义性
我发现了几个使用 {...}
的新初始化语法示例。但这些例子已经很古老了。我只是想再核实一下——目前的情况还如描述的那样吗?
在每个上下文(尤其是模板)中,以下源片段始终是无歧义的——无论T
和v
是什么。
T{v};
-- 始终构造一个T
类型的临时对象,并使用值v
对其进行初始化。T x{v};
-- 用值v
初始化类型为T
的变量x
。T x = {v};
-- 相同,因为=
在这里只是可选的。T a[] = {v};
-- 使用值v
初始化数组的所有元素。p = new T{v};
-- 在堆上分配一个T
类型的对象,并使用值v
对其进行初始化。
因此,这仍然是正确的,告诉人们“更喜欢 {}
语法,并且您的源代码不会有不同的含义,具体取决于 T
和 <代码>v是“。
I found a couple of example of the new Initializer Syntax using {...}
. But the examples are quite old. I just want to cross-check -- is the current situation still as described?
In every context (especially templates), the following source fragments always are non-ambiguous -- no matter what T
and v
are.
T{v};
-- always constructs a temporary of typeT
and initialized it with valuev
.T x{v};
-- initialized a variablex
of typeT
with valuev
.T x = {v};
-- same, because=
is just optional here.T a[] = {v};
-- initializes all elements of an array with the valuev
.p = new T{v};
-- allocates an object of typeT
on the heap and initializes it with valuev
.
Therefore, it is still true, telling people "Prefer the {}
-syntax, and your source code will not have different meanings, depending on what T
and v
are".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
T x{v};
-- 用值 v 初始化类型为 T 的变量 x。T x = {v};
-- 相同,因为 = 在这里只是可选的。就 N3291(最终标准之前的最后一个工作草案)而言,对于所有可能的
v
和T
来说,这些都不相同。主要区别如下。第一个是显式构造函数调用,因此它可以选择声明为显式的构造函数。第二个是不是显式的构造函数调用(即使它会调用构造函数)。因此它不能选择
显式
构造函数。从 13.3.1.7 开始:
这样做的目的是确保您在使用复制初始化时不会意外执行值的
显式
转换,即使使用{}
语法也是如此。T x{v};
-- initialized a variable x of type T with value v.T x = {v};
-- same, because = is just optional here.As far as N3291 (the last working draft before the final standard) is concerned, these are not the same for all possible
v
andT
.The principle difference is the following. The first is an explicit constructor call, and it therefore may select a constructor declared
explicit
. The second is not an explicit constructor call (even though it will call a constructor). Therefore it cannot selectexplicit
constructors.From 13.3.1.7:
The purpose of this is to ensure that you cannot accidentally perform an
explicit
conversion of a value when using copy initialization, even with{}
syntax.