为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身

why structured bindings don't return references to struct members using `auto&` but the members themselves are returned

本文关键字:成员 返回 引用 结构化 结构 绑定 auto 为什么      更新时间:2023-10-16

我认为使用结构化绑定和auto&说明符,我可以获取对结构成员的引用并直接使用它们,而不是通过结构。

但是,以下代码有效,静态断言成立:

struct Test
{
int i;
char c;
double d;
};
Test test{ 0, 1, 2 };
auto& [i, c, d] = test;
i = 4;
c = 5;
d = 6;
// i, c, d are not references !
static_assert(!std::is_same_v<decltype(i), int&>);
static_assert(!std::is_same_v<decltype(c), char&>);
static_assert(!std::is_same_v<decltype(d), double&>);
cout << &i << " == " << &test.i << " (" << std::boolalpha << (&i == &test.i) << ")" << endl; // (true)
cout << test.i << ", " << (int)test.c << ", " << test.d << endl; // 4, 5, 6

但我认为C++不允许一个变量具有多个名称,除非一个是真正的变量,其他变量是引用,但在这种情况下,变量itest.i相同,并且它们都不是引用。

在数组和类型案例中,结构化绑定不是引用 - 它们是相应成员的别名。这样做的主要原因是支持位域。不能引用位域,但可以具有位域的别名:

struct X {
uint8_t a : 2;
uint8_t b : 6;
};
void f(X& x) {
auto& [a, b] = x; // fine, a just means "x.a"
auto& a2 = x.a;   // error
}

除此之外,decltype()对结构化绑定执行一些特殊操作 - 仅当绑定引用的成员是引用类型时,它才会为您提供引用类型,如下所示:

struct Y {
int& a;
int b;
};
void f(Y& y) {
auto& [a, b] = y;
// decltype(a) is int&, decltype(b) is int
}