c++ - 为什么结构化绑定不使用`auto&`返回对结构成员的引用,但返回成员本身
问题描述
我认为使用结构化绑定和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++ 不允许一个变量有多个名称,除非一个是真实变量,而其他变量是引用,但在这种情况下,变量i
是相同的,test.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
}
推荐阅读
- java - 谷歌云 - 与本地机器相比,数据存储区太慢了
- node.js - 有没有办法在同一个域/服务器上运行用不同语言编写的完全不同的项目?
- php - 计数我做了一个 preg_replace 我通过字典运行匹配并将其用作放置的项目?
- python - 如何在具有下拉菜单且包含日期的 bigquery 中打开数据集
- c++ - 我可以在静态对象中读取文件(.txt)吗?C++
- node.js - mongoose 可以在一次查询中返回文档或仅返回其中一个字段吗?
- java - 为什么 dto 被转换为 Map?
- python - 如何找到包含相同值或值超集的键值对
- java - Project Reactor - 如何处理来自 Flux.interval 的 OverflowException?
- c# - Gmail 错误:System.Net.Mail.SmtpException:SMTP 服务器需要安全连接或客户端未通过身份验证