[Issue 9087] Value modified in foreach warning

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Nov 28 14:17:34 PST 2012


http://d.puremagic.com/issues/show_bug.cgi?id=9087



--- Comment #7 from bearophile_hugs at eml.cc 2012-11-28 14:17:31 PST ---
(In reply to comment #6)

Thank you for your answers, Jonathan.

> And why should we take a performance hit with a required copy

I think you are missing something. If you use "ref" or "const ref" no copy is
performed:

// program#4
struct S { int x; }
void main() {
    auto items = [S(1), S(2), S(3)];
    foreach (ref it; items)
        it.x++;
}


In program#3 there was a copy because in that case the programmer do wants a
copy.


> Honestly, I don't think that I have _ever_ seen a bug caused by this.

Assuming you have understood what's the bug-class I am talking about (and I am
not sure of this, given what I think is the above mistake of yours), yours is
only one data point. Mine is another data point, and in my code the unwanted
modification of a struct in a foreach loop has caused me several bugs. And in
the D newsgroup some other persons have said they make mistakes about this.
Another important data point is the design of C#, that in the case discussed in
this enhancement request disallows mutation. So in the end it's quite more one
person against your case.


> That doesn't mean that it can't happen or that it hasn't happened, but I don't
> think that it's even vaguely worth worrying about.

It seems to be a common enough situation that's recognized as bug prone. So
it's worth worrying about, because this class of problems is not hard to
prevent.


> You have a habit of trying to get warnings created for every
> single stray mistake that you think a programmer might make,

I agree that raising a warning here is a suboptimal solution. I think the right
solution is to do something more similar to C#, and disallow the struct
mutation in foreach unless you put a "ref" tag.

The total number of warnings I am asking for in Bugzilla is really small,
probably around 3-4.


> There comes a point where you have
> to let the programmer do their job and assume that they're not going to be an
> idiot.

We are *very* far from that in D, for a D programmer there are plenty of things
to take care of to write correct programs :-)

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list