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?
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.
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.
The == operator can be used to check if two object 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With