Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++11 "auto" keyword retrieve "cv-qualifier" at all? I've got conflict samples

It's said the "auto" doesn't retrieve cv-qualifier, so I did an experiment:

const int i = 0;
auto r1 = i;
auto& r2 = i;
r1 = 3;//ok
r2= 3;//compilation error

Seems when constructing a value, cv-qualifier is not with the new variable, but used with reference "&", the cv-qualifier is with it. Why is that, does auto retrieves "cv-qualifier" at all?

like image 818
Troskyvs Avatar asked Oct 26 '25 09:10

Troskyvs


1 Answers

auto deduction works the same as template deduction for most cases. Just auto drops all cv-qualifiers, but auto& maintains the cv-qualifications of the referred type. If auto& dropped the qualifiers, you would be able to take a non-const reference to a const object, which would be bad! This works exactly the same way as:

template <class T> deduce(T );
template <class T> deduce_ref(T& );

deduce(i);     // calls deduce<int>
deduce_ref(i); // calls deduce<int const>

Since r2 is a reference to const int, you can't assign to it. But r1 is just a copy of i.

like image 69
Barry Avatar answered Oct 28 '25 22:10

Barry