Variables marked as const using structured bindings are not const

后端 未结 1 1206
迷失自我
迷失自我 2020-12-24 07:27

I have been writing a set of classes to allow for a simple python-like zip-function. The following snippet works (almost) just as expected. However, the two var

相关标签:
1条回答
  • 2020-12-24 08:26

    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
    

    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.

    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).

    0 讨论(0)
提交回复
热议问题