C++0x 广义初始值设定项的非歧义性

发布于 2024-11-30 11:32:25 字数 725 浏览 3 评论 0原文

我发现了几个使用 {...} 的新初始化语法示例。但这些例子已经很古老了。我只是想再核实一下——目前的情况还如描述的那样吗?

在每个上下文(尤其是模板)中,以下源片段始终是无歧义的——无论Tv 是什么。

  • 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 type T and initialized it with value v.
  • T x{v}; -- initialized a variable x of type T with value v.
  • T x = {v}; -- same, because = is just optional here.
  • T a[] = {v}; -- initializes all elements of an array with the value v.
  • p = new T{v}; -- allocates an object of type T on the heap and initializes it with value v.

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

○闲身 2024-12-07 11:32:25
  • T x{v}; -- 用值 v 初始化类型为 T 的变量 x。
  • T x = {v}; -- 相同,因为 = 在这里只是可选的。

就 N3291(最终标准之前的最后一个工作草案)而言,对于所有可能的 vT 来说,这些都不相同。

主要区别如下。第一个是显式构造函数调用,因此它可以选择声明为显式的构造函数。第二个是不是显式的构造函数调用(即使它会调用构造函数)。因此它不能选择显式构造函数。

从 13.3.1.7 开始:

在复制列表初始化中,候选函数都是 T 的构造函数。但是,如果选择显式构造函数,则初始化是格式错误的。

这样做的目的是确保您在使用复制初始化时不会意外执行值的显式转换,即使使用{}语法也是如此。

  • 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 and T.

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 select explicit constructors.

From 13.3.1.7:

In copy-list-initialization, the candidate functions are all the constructors of T. However, if an explicit constructor is chosen, the initialization is ill-formed.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文