gpt4 book ai didi

c++ - 列表初始化的复制省略,它在标准中的何处规定?

转载 作者:可可西里 更新时间:2023-11-01 15:25:06 26 4
gpt4 key购买 nike

[dcl.init]/17.6 ,明确写到对于括号初始化的情况,会发生复制省略:

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. [ Example: T x = T(T(T())); calls the T default constructor to initialize x.  — end example ]

但是在列表初始化的情况下,上面的段落不适用,我没有发现任何类似的东西。参见 [dcl.init.list] .

那么为什么在这种情况下存在复制省略:T x{T(T())}; 根据 C++17 标准。

最佳答案

根据目前的草案,这种情况下没有复制省略。

考虑以下示例:

#include <iostream>
#include <initializer_list>

struct S {
S() {std::cout << "default\n";}
S(const S&) {std::cout << "copy\n";}
S(std::initializer_list<S>) {std::cout << "initializer list\n";}
};

int main()
{
S s = S{S()};
}

根据 Core Language Issue 2137 , 应选择以std::initializer_list 为参数的构造函数(Clang 可以选择复制构造函数或执行复制省略,即 is incorrect )。因此,此类列表初始化应考虑构造函数。

The problem is that when copy/move constructor is selected, it is reasonable to elide this copy/move.事实上,Core Language Issue 2327已经解决了这个缺陷。

关于c++ - 列表初始化的复制省略,它在标准中的何处规定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49535106/

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