Why reference const can be re-assigned in for-statement?

后端 未结 3 1288
夕颜
夕颜 2021-01-07 16:54

I\'m new to C++, and I\'m confused about this:

vector v = { 1,2 };
const int &r1 = v[0];
//r1 = v[1];  // compiler will show error.
         


        
3条回答
  •  温柔的废话
    2021-01-07 17:27

    According to the C++11 standard [stmt.ranged]:

    for (const int &r2 : v) std::cout << r2;
    

    where ¹v is a vector, is equivalent to:

    {
        auto && __range = (v);
        for (auto __begin = __range.begin(), __end = __range.end(); __begin != __end; ++__begin)
        {
            const int &r2 = *__begin; // <-- new variable in each iteration
            std::cout << r2;
        }
    }
    

    Demo

    The reference const r2 is assigned twice, right?

    No. There is a new r2 variable in each iteration.


    ¹ The range based for can also be used with other kinds of collections, including raw arrays. The equivalence given here is what the general equivalence becomes for a std::vector.

提交回复
热议问题