I admit my C++ skills are a bit rusty and I’m diving right into C++11 for a new project I’m about to begin. I’ve just found this confusing behaviour where if I write
void MyClass::update() {
for(SomeClass &i : _list) {
i.doStuff();
}
}
or
void MyClass::update() {
for(SomeClass i : _list) {
i.doStuff();
}
}
it seems to work exactly the same, with _list being a std::list<SomeClass>. So I was wondering what’s the use of the ref here, since I’m clearly missing something. I should mention I’m using Apple LLVM 4.0 that comes with Xcode 4.4.1 (4F1003).
Please, feel free to mock and make fun of me if this is an ourageously silly question, I could really use some good ol’ head slapping 🙂
The reference has nothing to do with the container, but with the element you are taking out of it. In the first case you are accessing the element which is in the list and modifying that, in the second case, you make a copy of the element and then change the copy, which will go out of scope anyway.