gpt4 book ai didi

c++ - 对由非 T 类型的值初始化的 const T 的引用

转载 作者:太空狗 更新时间:2023-10-29 21:00:25 25 4
gpt4 key购买 nike

对于下面的代码:

struct A {
explicit A(int) {}
};

const A& a(1); // error on g++/clang++/vc++
const A& b = 1; // error on g++/clang++/vc++
const A& c{1}; // ok on g++/clang++, error on vc++
const A& d = {1}; // error on g++/clang++/vc++

4 个初始化中哪个(哪些)是合法的?

如果我们首先忽略 vc++,似乎 direct-init 和 copy-init 之间的区别在这里表现不一致。如果第三个是格式正确的,因为它是 direct-init,为什么第一个也是 direct-init 编译失败?这背后的逻辑是什么?或者这只是 g++/clang++ 的一个错误,而 vc++ 可以正确处理它?<​​/p>

最佳答案

如果您正在使用braced-init-lists 并且初始化的目标类型是引用:

[dcl.init.list]/3(来自 n3690)

  • 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 (see below) 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 copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary. [Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. — end note]

  • Otherwise, if the initializer list has no elements, the object is value-initialized.

对于 const A& c{1};const A& d = {1}; 这两个示例,上面引用的第二个项目符号适用。第一个直接列表初始化一个const A,第二个复制列表初始化一个const A。选择 explicit 构造函数的复制初始化格式错误,请参阅 [over.match.list]/1。


如果您不使用 braced-init-lists,据我所知,复制初始化和直接初始化之间没有区别。 [dcl.init.ref]/5 的最后一条适用于所有情况:

  • Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.

复制初始化不能选择一个explicit ctor,见[over.match.copy]/1(这是不可行的)。


结论:

const A& c{1};

是合法的。另一个不是,因为它们要么使用复制初始化,要么使用复制列表初始化,并且唯一可行/选定的 ctor 是 explicit

关于c++ - 对由非 T 类型的值初始化的 const T 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22128890/

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