Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference referring to multiple objects, how is it possible? [duplicate]

Tags:

c++

c++11

In one of the C++ books i am reading :

int v[] = {0,1,2,3,4,5,6,7,8,9};
for (auto& x : v)

When next line in the book says :

".. a reference cannot be made to refer to a different object after its initialization..."

x refers to all v's object, how does it work?

like image 276
schanti schul Avatar asked Oct 03 '17 09:10

schanti schul


People also ask

Can two or more reference refer to the same object justify?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

How many objects can be referenced from the same variables?

11. How many objects can be referenced from the same variables? Explanation: There should not be any confusion in how many references can be made from a single variable. A single variable can only point to one object at a time.

How do you know if two objects are the same reference?

The == operator can be used to check if two object references point to the same object.

What happens when two references point to the same object?

Object reference equality: when two object references point to the same object. Object value equality: when two separate objects happen to have the same values/state.


2 Answers

Given a range-based for loop

for ( range_declaration : range_expression ) loop_statement

It is equivalent to

{
    auto && __range = range_expression ; 
    auto __begin = begin_expr ;
    auto __end = end_expr ;
    for ( ; __begin != __end; ++__begin) { 
        range_declaration = *__begin; 
        loop_statement 
    } 
}

Here range_declaration is your auto& x, it is initialized to refer to each element at each iteration, not rebinding the same reference.

like image 146
Passer By Avatar answered Nov 15 '22 14:11

Passer By


x refers to all v's object

Not at the same time. Each time through the loop x is a new local variable that refers to a single array element.

In pseudo code¹, it's like

for (int* it = std::begin(v); it != std::end(v); ++it)
{
    int& x = *it; // new local variable
    // ...
}

¹ For specifics, refer here http://en.cppreference.com/w/cpp/language/range-for

like image 35
sehe Avatar answered Nov 15 '22 15:11

sehe