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

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

    No it's not assigned twice. r2 exists from the start of the iteration (a single round over the loop body) until the end of the iteration. r2 in the next iteration is another object by the same name. Each iteration has their own r2 and each of them is initialized separately.

提交回复
热议问题