11

I'm trying to understand structured binding introduced in C++17. The explanation on cppreference is not obvious to me, but it looks like

cv-auto ref-operator [x, y, z] = ...

is roughly equivalent to (not to consider array case)

cv-auto ref-operator unique_name = ...
#define x unique_name.member_a
#define y unique_name.member_b
#define z unique_name.member_c

The key point here is that x y z are not independently defined variables, but just aliases of the return value members. And cv-auto ref-operator applies to the return value, not the aliases (the syntax may be misleading here). For instance, see the cppreference example

float x{};
char  y{};
int   z{};

std::tuple<float&,char&&,int> tpl(x,std::move(y),z);
const auto& [a,b,c] = tpl;
// a names a structured binding of type float& that refers to x
// b names a structured binding of type char&& that refers to y
// c names a structured binding of type const int that refers to the 3rd element of tpl

If a b c are independently defined variables, with const auto& applying to them, c cannot be of type const int.

From a practical point of view, what are the key points this analogy failed to catch?

4

1 回答 1

9

从另一个角度考虑这一点可能会很有见地。

在 C++ 中,我们已经有了变量、具有名称的int a = 5对象和不是变量且没有名称的对象:*new int. 结构化绑定是一种为变量的所有部分命名的方法,而整个变量没有明确的名称。所以它是[x,y,z] 用三个成员一起命名一个变量的组合。

重要的是,它们一起命名一个对象,因此编译器实际上必须对对象进行布局。自变量可以独立放置在堆栈上。但是对于结构化绑定,编译器不能这样做(正常as-if规则除外)

因此,当我们将组合[x y z]视为变量的名称时,很明显auto const& [x y z]使组合成为const&变量。

然后我们必须考虑具体的个人名称x和含义。您的问题将它们总结为yz

cv-auto ref-operator unique_name = ...
#define x unique_name.member_a
#define y unique_name.member_b
#define z unique_name.member_c

这有点棘手。从哪里来member_a?似乎unique_name有一个member_a. 您已经排除了具有[0]. 元组有get<0>(tpl). member_a后面很可能有一个get<0>,但名称 member_a 可能是私有的。member_a也可能比get<0>.

但是是的,对于最简单的情况,一个struct没有位域的简单,确实会有一个对应的member_a.

于 2018-04-12T15:40:02.877 回答