且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用结构化绑定标记为const的变量不是const

更新时间:2023-11-11 15:29:10

您有一个引用,这意味着引用本身将是 const 限定的(格式不正确,但在这种情况下忽略),而不是它引用的值。

You have a tuple of a reference, which means that the reference itself will be const qualified (which is ill-formed but in this context ignored), not the value referenced by it.

int a = 7;
std::tuple<int&> tuple = a;
const auto&[aa] = tuple;
aa = 9; // ok

如果您看 std :: get 已定义,您将看到它为结构化结构返回 const std :: tuple_element< 0,std :: tuple< int&>& 绑定以上。由于第一个元组元素是引用,因此 const& 不起作用,因此可以修改返回值。

If you look how std::get is defined, you'll see that it returns const std::tuple_element<0, std::tuple<int&>>& for the structured binding above. As the first tuple element is a reference, the const& has no effect, and thus you can modify the return value.

真的,如果您有一个类指针/引用成员可以在 const 限定成员函数(即指向/引用的值)中进行修改,那也是一样。

Really, it's same thing if you have a class pointer/reference member that you can modify in a const qualified member function (the value pointed/referenced that is).