In C++11 we can now do :
void dosomething( std::vector<Thing>& things )
{
for( Thing& thing : things )
{
dofoo( thing );
wiizzz( thing );
tadaa( thing );
}
}
I know that the addition and use of lambda is syntactic sugar but it provide interesting optimization opportunities.
What about the for loop? Is it only syntactic sugar or can the compiler optimize some cases that it couldn’t or would be too hard to do with handwritten loop?
It’s just a syntactic sugar since the standard says that it’s equivalent to a loop with iterators [ Edit: this means it doesn’t provide any additional information to the compiler compared to the equivalent for loop — end edit ]. You may get a better performance though since it’s equivalent to:
while most people may write:
which may be slower if the con.end(), iter++ or *iter are not trivial.
[ Edit:
Not really. Unlike for loop it allows the compiler to capture the stack-frame base pointer directly, for variables captured by reference this saves one address indirection per each use, compared to a handcrafted function object. — end edit ]