[Issue 11934] Allow `ref` in `foreach` over range iff `front` returns by `ref`

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Feb 21 08:08:06 UTC 2019


https://issues.dlang.org/show_bug.cgi?id=11934

Simen Kjaeraas <simen.kjaras at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |simen.kjaras at gmail.com

--- Comment #3 from Simen Kjaeraas <simen.kjaras at gmail.com> ---
Simplified example:

import std.stdio;
import std.algorithm;

struct A {
    this(int i) { writeln("ctor ", &this); }
    ~this() { writeln("dtor ", &this); }
    this(this) { writeln("postblit ", &this); }
}

unittest {
    writeln("Without ref:");
    foreach(r; [1].map!(x => A(x))) { }
    writeln("With ref:");
    foreach(ref r; [1].map!(x => A(x))) { }
}

As we can see from the output, the dtor is correctly called in the non-ref
case, but not in the ref case. Memory addresses are the same in both cases, and
are stack addresses, so it's not a case of 'allocate on heap and let GC sort it
out'.

As Denis points out though, it may be better for this not to compile than to
compile and silently do something other than expected (even though the ref'ed
struct is mutated, this is not reflected anywhere since it's a temporary).

--


More information about the Digitalmars-d-bugs mailing list