ref, safety, and warnings (was: ref and out required for function calls)

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Sep 23 10:37:23 PDT 2012


On 9/7/12, Kevin McTaggart <kevin.mctaggart at drdc-rddc.gc.ca> wrote:
> snip

There's one thing nobody mentioned yet, and that is that we're already
using this syntax in the language -- in foreach loops:

struct Foo { int x; }
Foo[] arr = [{4}, {5}, {6}];

foreach (idx, ref val; arr)
{
    val.x = idx;
}

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. Structs and classes have different semantics
and when you're working in a large codebase that uses a combination of
classes and structs it's too easy to forget to add 'ref' to a foreach
parameter because you're looping over struct instances of some range
rather than class references.

I'd rather this be a special warning since enabling it by default
might be annoying if you really want to opAssign to temporaries.

I think the current mechanism we have (shove all warnings into the
"-w" switch and offer no customization) is lacking. I'd propose we
kept the current '-w' switch but also added options only enable or
disable specific warnings, e.g.:

dmd -we001 -we002 -> only enable warnings 001 and 002
dmd -w -wd001 -wd002 -> enable all warnings, except 001 and 002 which
are disabled

Then we could keep a list of warnings on dlang.org and provide helpful
info on when these warnings occur and what the user can do to fix his
code. For example look at how empty the warnings page is now:
http://dlang.org/warnings.html

I'd be willing to help out write the new warnings page.


More information about the Digitalmars-d mailing list