I’m using Visual Studio 2010. One feature I’d like to use, what has been left out of VS2010, but is included in VS2012 is the range-based for-loop.
In VS2012 you can do neat and super-tidy for-loops like:
for( auto& it: myElements )
it->something();
So far, the closest I could get in VS2010 is this syntax:
for( auto it = myElements.begin(), end = myElements.end(); it != end; it++ )
it->something();
Upon reading some related questions, I found that using boost\foreach I have access to the following macro:
BOOST_FOREACH( auto it, myElements ){
it.something();
}
My problem with this method is that it gives a copy (or something similar), not a pointer. Here is where I get confused. The foreach reference says the following:
It does no dynamic allocations, makes no virtual function calls or
calls through function pointers, and makes no calls that are not
transparent to the compiler’s optimizer.
What does it mean? Isn’t it a copy?
How can I get a pointer back from BOOST_FOREACH? Or should I use some other boost function?
I’ve seen this syntax in other questions here:
BOOST_FOREACH( auto& it, myElements ){
it->something();
}
however this doesn’t compile for me and throws errors in the editor. What’s wrong with this? Why did I find it as a valid code on many other questions here?
Are there any nice and tidy solution in VS2010 for a range-based for-loop? (including using boost)
The main question is, do you have a container of pointers? Even in VS2012,
for(auto& it: myElements) it->something();only works on containers of (smart) pointers. The&tells you thatitis a reference, and the->tells you that it’s a pointer. That’s not a contradiction; you can have references to pointers.But why would you want a pointer anyway? A reference is far more idiomatic.