为什么constby-value结构绑定允许用户修改引用的变量?
我对结构绑定很困惑。即使我在这个例子中使用const和按值(没有&)结构绑定:
#include <iostream>
#include <tuple>
int main()
{
int x = 0;
std::tuple<int&> p(x);
const auto [a] = p;
a++;
std::cout << x << 'n';
}
它仍然修改x和打印1:https : //gcc.godbolt.org/z/jc8hxE8M6
你能解释一下为什么它会这样工作,如果我&之前添加[a]或删除想要改变const吗?
回答
请参阅cppreference上的示例:
前面的声明部分
[适用于隐藏变量 e,而不适用于引入的标识符。int a = 1, b = 2; const auto& [x, y] = std::tie(a, b); // x and y are of type int& auto [z, w] = std::tie(a, b); // z and w are still of type int& assert(&z == &a); // passes
哪里e指
结构化绑定声明首先引入一个唯一命名的变量(这里用 e 表示)来保存初始化器的值,如下所示: [...]
该const在你的例子并不适用于a,为什么它仍然可以通过下面的例子演示有用:
int a = 1; const auto& [x] = std::make_tuple(a); // OK, not dangling auto& [y] = std::make_tuple(a); // error, cannot bind auto& to rvalue std::tuple auto&& [z] = std::make_tuple(a); // also OK