foreach by value iteration

Peter Alexander peter.alexander.au at gmail.com
Sun Feb 26 00:01:23 PST 2012


I just got bitten by this again. It usually looks something like 
this:

-----------------
struct Vector
{
     ...
     void normalize() { this /= length; }
}

Vector[] vs;
...
foreach (v; vs)
     v.normalize();
-----------------

The bug here is that the loop does nothing because it is 
normalizing a temporary copy of the vector, rather than the 
vectors in the array.

Am I the only person that gets caught by this trap?

Perhaps the loop variable should be implicitly const so that this 
type of thing won't happen?


More information about the Digitalmars-d mailing list