Functionality of Array<t> in range based for loop


#1

I have been trying to work out for a while now the exact functionality of this and I am afraid it still illudes me. Sometimes it seems to work fine, sometimes it only seems to see the first element and sometimes it seems to not do anything. I think it may be something like it giving me a copy rather than a reference so when I am only using the value and not changing it then it works but I thought I would ask here since I am a little confused. So for example what should this produce?

 

Array<int> variable;
for (auto & v : variable) {
    v++;
}

Compared to this?

int i = 0;
Array<int> variable; 
for (const auto & v : variable) 
{ 
    i += v; 
}

Sorry for the slightly vague question. It's been a rather strange problem. I'm sure it is consistent it's just me doing the wrong tests.


#2

The Array iterator is designed for reading, not modifying, and you shouldn't assume it'll give you a reference into the original list rather than a copy. But... it is implemented in such a way that it would work like that. I'd be surprised if something as simple as

Array<int> x;

for (int& i : x)
    ++i;

..didn't increment the elements as you'd expect it to. Perhaps in your real code you're making a copy of the array itself in the course of passing it into the for loop?

 


#3

Thanks! That is how I would expect it to run. I will look closer into my code. I probably have something wierd going on in there.