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

后端 未结 3 1283
夕颜
夕颜 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:17

    The ranged-based for looks like this:

    attr(optional) for ( range_declaration : range_expression ) loop_statement

    where range_declaration is

    range_declaration - a declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction

    So each iteration a new declaration is introduced, the reference only exists until the next loop iteration.

提交回复
热议问题