gpt4 book ai didi

c++ - 当参数转换为目标类型时,复制构造函数省略以直接初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:03:54 24 4
gpt4 key购买 nike

这个问题是关于c++标准的措辞。

所有编译器,我认为这是应该的,在下面(assembly here)省略对象b初始化的复制构造函数:

struct B;

struct A{
operator B();
};

struct B{
B(const B&);
B(B&&);
};

void test(A a){
B b(a);
}

但是当我阅读标准时,我不明白为什么会发生这种省略(粗体)[dcl.init]/17.6.2 :

Otherwise, if the initialization is direct-initialization, [...], constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one is chosen through overload resolution ([over.match]). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

具体说是调用了构造函数。但是没有编译器这样做。

我想我遗漏了什么或者没有正确阅读标准。我该如何阅读标准?


这与专门要求复制省略的标准的前后段落形成对比 [dcl.init]/17.6.1 :

If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object.

和[dlc.init]/17.6.3:

Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversions that can convert from the source type to the destination type [...] The function selected is called with the initializer expression as its argument; [...] The call is used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization.

最后一句话让我回到 [dcl.init]/17.6.1,这也意味着复制省略。

最佳答案

@T.C.在评论中回答,这是核心语言问题 CWG2327 .

关于c++ - 当参数转换为目标类型时,复制构造函数省略以直接初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297545/

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