For me, it seems that for generality you should always add ref into foreach loop variable. The reason is this:

import std.experimental.all;

struct NoCopies
{   @disable this(this);
    int payload;
}

void main()
{   auto range = new NoCopies[20];
    foreach(const ref el; range) el.payload.writeln;
}

Without ref qualifier in el, this won't work because it would make a copy. Unlike ref as a function argument, it does not enforce refness:

import std.experimental.all;

void main()
{   auto range = iota(20).map!(x => x + 2);
    foreach(const ref el; range) el.writeln;
}

This compiles, even though range elements are rvalues.

This seems to imply, for me, that for generality one should always use ref in foreach loop variables. If the vairable has to be guarded against changes, it should const ref, not unqualified.

But considering unqualified is the default, I am probably missing something here. Performance?

Reply via email to