I'm new to C++, and I'm confused about this:
vector<int> v = { 1,2 };
const int &r1 = v[0];
//r1 = v[1]; // compiler will show error.
I understand that reference const r1
cannot be re-assigned. But look at the codes below:
for (const int &r2 : v) cout << r2;
Why wouldn't that go wrong? The reference const r2
is assigned twice, right?
According to the C++11 standard [stmt.ranged]:
where ¹
v
is avector
, is equivalent to:Demo
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 astd::vector
.The ranged-based
for
looks like this:where range_declaration is
So each iteration a new declaration is introduced, the reference only exists until the next loop iteration.
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 ownr2
and each of them is initialized separately.