gpt4 book ai didi

c++ - 构造中的单个值与构造的参数列表

转载 作者:可可西里 更新时间:2023-11-01 16:39:32 25 4
gpt4 key购买 nike

这个问题属于这个 code snippet转载如下:

struct A { 
A():b(0) { }
A(const A&, int b = 0):b(b) { }
int b;
};

int main() {
A a;

const A& a1 = { a };
const A& a2 = { a, 1 };
a.b = 2;
std::cout << a1.b << a2.b << std::endl;
}

a1 赋值的右侧可以是构造中的单个值或构造的参数列表。标准中是否有任何地方指定哪种解释优先?对于a2,如果我没有理解错的话,它是一个临时A的构造,地址分配给a2。

顺便说一句,在 Coliru 中通过 clang++ 编译此代码产生输出 21。gcc++-4.8 输出 01。

最佳答案

由于缺陷报告,自 C++11 标准发布以来,列表初始化的定义发生了很大变化。

来自 n3485 草案(标准发布后,有一些更正但没有 C++1y 特性)[dcl.init.list]/3

List-initialization of an object or reference of type T is defined as follows:

  • If T is an aggregate [...]
  • Otherwise, if the initializer list has no elements [...]
  • Otherwise, if T is a specialization of std::initializer_list<E> [...]
  • Otherwise, if T is a class type [...]
  • Otherwise, if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element; if a narrowing conversion is required to convert the element to T, the program is ill-formed.
  • Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary
  • [...]

在委员会的 github 存储库 (ce016c64dc) 的最新草案中,此处仅对一点 [dcl.init.list]/3 进行了细微更改:

  • Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary.

来自 n3242 草案(标准之前)[dcl.init.list]/3:

List-initialization of an object or reference of type T is defined as follows:

  • If the initializer list has no elements [...]
  • Otherwise, if T is an aggregate [...]
  • Otherwise, if T is a specialization of std::initializer_list<E> [...]
  • Otherwise, if T is a class type [...]
  • Otherwise, if T is a reference to class type or if T is any reference type and the initializer list has no elements, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary.
  • [...]

(我现在没有标准本身的拷贝。)


让我们假设您的编译器对缺陷报告实现了建议的解决方案。然后,第一个例子

const A& a1 = { a };

初始化像const A& a1 = a; (没有临时的);和第二个例子

const A& a2 = { a, 1 };

初始化像const A& a2 = A(a,1); .

关于c++ - 构造中的单个值与构造的参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19574351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com