强制复制省略是否适用于通过结构化绑定(bind)进行的分解?这适用于以下哪些情况?
// one
auto [one, two] = std::array<SomeClass>{SomeClass{1}, SomeClass{2}};
// two
auto [one, two] = std::make_tuple(SomeClass{1}, SomeClass{2});
// three
struct Something { SomeClass one, two; };
auto [one, two] = Something{};
我怀疑只有第三种情况允许复制省略,因为前两种情况将通过 std::get<>
“分解”和 std::tuple_size<>
和 std::get<>
当参数是右值时返回 xvalues
引用标准也很好!
最佳答案
Does mandatory copy elision apply to decomposition via structured bindings? Which of the following cases does that apply to?
是的,所有这些。结构化绑定(bind)的重点是为您提供对您要绑定(bind)的类型的解构元素的命名引用。这个:
auto [one, two] = expr;
只是语法糖:
auto __tmp = expr;
some_type<0,E>& a = some_getter<0>(__tmp);
some_type<1,E>& b = some_getter<1>(__tmp);
在哪里 some_type
和 some_getter
取决于我们要解构的类型(数组、类元组或具有所有公共(public)非静态数据成员的类型)。
强制复制省略适用于 auto __tmp = expr
行,其他行均不涉及拷贝。
评论中的示例有些困惑,所以让我详细说明一下:
auto [one, two] = std::make_tuple(Something{}, Something{});
那个 expands into :
auto __tmp = std::make_tuple(Something{}, Something{}); // note that it is from
// std::make_tuple() itself that we get the two default constructor calls as well
// as the two copies.
using __E = std::remove_reference_t<decltype(__tmp)>; // std::tuple<Something, Something>
那么,由于 __E
是 not an array type但是 is tuple-like ,我们通过 unqualified call to get
looked up in the associated namespace of __E
引入变量.初始化程序将是 xvalue类型为 rvalue references :
std::tuple_element_t<0, __E>&& one = get<0>(std::move(__tmp));
std::tuple_element_t<1, __E>&& two = get<1>(std::move(__tmp));
请注意,虽然 one
和 two
都是对 __tmp
的右值引用, decltype(one)
和 decltype(two)
将both yield Something
而不是 Something&&
.
关于c++ - 复制省略是否适用于结构化绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698326/