The logic of the following is confusing me. It compiles ok but the result of foo
is an rvalue. It is a temporary. Why am I then allowed to get non constant references to items in the container?
#include <array>
std::array<int,3> foo(){
return std::array<int,3>{0,1,2};
}
int main(){
for(int & item: foo())
item = 0;
}
The range based for loop has the syntax
and it expands into
as you can see, the rvalue's lifetime gets extended by
__range
, so it's valid to have lvalue references into the collection__range
binds to. Once the loop is over,__range
will go out of scope destroying the rvalue object that was created.This is why it works even though you are modifying an object that is destined to be destroyed.