Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Does "auto" keyword retrieves cv-qualifier at all? I've contradictory sample

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.

like image 286
Hind Forsum Avatar asked Jun 09 '16 08:06

Hind Forsum


1 Answers

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.

like image 69
Vittorio Romeo Avatar answered Nov 13 '22 06:11

Vittorio Romeo