Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "auto const&" not read-only? [duplicate]

#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:

  1. Why am I allowed to write to xb when it is specified as auto const&? Shouldn't this fail to compile?

  2. 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!

like image 469
user5406764 Avatar asked Apr 21 '18 15:04

user5406764


1 Answers

  1. 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);
    
  2. 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.

like image 162
Chris Dodd Avatar answered Sep 20 '22 17:09

Chris Dodd