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