I've got program like below:
struct A{ int i; };
int main()
{
const int i = 0;
auto ai = i;
ai = 2; // OK
const A buf[2];
for(auto& a : buf)
{
a.i = 1; // error!
}
std::cout << buf[0].i << buf[1].i << std::endl;
}
The first auto ai = i;
has no problem, seems auto
doesn't retrieve c/v qualifier, as ai
can be modified
But the for loop fails compilation as--error: assignment of member A::i
in read-only object
I knew that auto
doesn't retrieve &
feature,
my question is: does auto
retrieve c/v qualifier like in my case?
My test program seems to give contradictory hints.
You are copying ai
here, not modifying it:
const int i = 0;
auto ai = i;
The code above is equivalent to:
const int i = 0;
int ai = i;
If you try to take a non-const
reference, you will get a compile-time error:
const int i = 0;
auto& ai = i;
ai = 5; // Error: assignment of read-only reference 'ai'
As suggested by Pau Guillamon, here's a snippet equivalent to the code above:
const int i = 0;
const int& ai = i;
ai = 5;
More details regarding the auto
specifier can be found on cppreference.
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