views:

329

answers:

2

In C++0x 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?

+15  A: 
ybungalobill
Are you sure it caches `end()`? This means you can't mutate the collection which is semantically different (for collections that don't invalidate iterators on insertion/deletion e.g. `list`).
Motti
I guess it assumes that the container will no change. If it will, using stl algorithms might be a better way.
Klaim
@Motti: the standard says explicitly that it's equivalent to the above code (well, a bit more complicated one because it's phrased in terms of ranges). Anyway if your container doesn't invalidate iterators, then end() is not invalidates. So what's the problem? You can change the container as long as you don't break this code.
ybungalobill
@ybungolobill right you are.
Motti
While I don't see any immediate optimization opportunities, the compiler can do whatever it wants under the as-if rule.
sellibitze
+5  A: 

Maybe, but probably not. It does eliminate the possible creating of an index/counter variable that won't be used. That's not required for a normal for loop either, but it's a lot more likely to happen just because it's what some people are accustomed to doing.

Realistically, it's unlikely to make any difference even from that though. I, at least, find it hard to imagine a compiler team so sophisticated that they have even the slightest aspiration toward supporting C++0x, that hasn't already handled the relatively trivial point of detecting and eliminating creating and incrementing a loop index that's never used.

Jerry Coffin