Why reference const can be re-assigned in for-stat

2020-03-08 07:15发布

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?

标签: c++
3条回答
对你真心纯属浪费
2楼-- · 2020-03-08 07:43

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.

查看更多
萌系小妹纸
3楼-- · 2020-03-08 07:46

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.

查看更多
放我归山
4楼-- · 2020-03-08 07:52

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.

查看更多
登录 后发表回答