foreach by value iteration

Jonathan M Davis jmdavisProg at gmx.com
Sun Feb 26 01:52:56 PST 2012


On Sunday, February 26, 2012 09:01:23 Peter Alexander wrote:
> 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?

That would be annoying. Sometimes, you _want_ to be able to alter the 
variable, even if it _is_ a copy. And if it's a reference type, then you don't 
have the problem at all, and making it const would be completely restrictive.

I really don't know how we could make it easier for you to avoid this error 
without making it impossible to other, useful things. But your code works if 
you use ref. You just have to remember to do that.

- Jonathan M Davis


More information about the Digitalmars-d mailing list