ref, safety, and warnings

bearophile bearophileHUGS at lycos.com
Sun Sep 23 11:36:46 PDT 2012


Andrej Mitrovic:

> However I'd like to see a custom compiler warning switch that 
> would
> warn me if I tried to call opAssign on a fundamental or struct 
> type in
> a foreach loop with a non-ref foreach parameter:
>
> foreach (idx, val; arr)
> {
>     val.x = idx;  // clearly a bug, but lacks warning
> }
>
> I've had *numerous* occasions over the last few years where 
> I've had this bug happen to me.

The same for me. Most people seem to not care for this problem, I 
don't understand why. But I think it's a common source for bugs 
in D programs. D design must take in account not just error-prone 
features inherited from C, but also to avoid bug-prone situations 
created by D-specific features.

C# designers have avoided this problem:
http://msdn.microsoft.com/en-us/library/04t3s14w.aspx

A possible solution is to require an explicit annotation if you 
want to modify just the copy:

foreach (idx, @copy val; arr)
     val.x = idx;


But maybe better is to do as in C# and turn "val" (and idx!) into 
a const on default, and require an annotation if you want to 
modify the copy:

foreach (idx, @mutable val; arr)
     val.x = idx;

Bye,
bearophile


More information about the Digitalmars-d mailing list