#include <tuple>
int main()
{
int xa = 1;
int ya = 2;
auto const& [xb, yb] = std::tuple<int&, int&>(xa, ya);
xb = 9; // Shouldn't this be read-only?
return xa + ya;
}
This not only compiles, but returns 11.
So two questions:
Why am I allowed to write to xb when it is specified as auto const&? Shouldn't this fail to compile?
Why can't I replace "auto const&" with "auto&" and have it compile? Both Clang (6.0) and g++ (7.3) complain with an error message like "non-const lvalue reference of type<...> cannot bind to temporary of type tuple<...>"
Thanks!
You're getting a const reference to a tuple of non-const references to ints. You're then breaking out that tuple into two non-const references. To make the int references const, you need to make the int references const:
auto const& [xb, yb] = std::tuple<const int&, const int&>(xa, ya);
The tuple you are creating is an unnamed temporary, so you can't bind a non-const reference to it, even though that reference is itself unnamed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With