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

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Jun 14 14:22:46 UTC 2018


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

Richard Cattermole <alphaglosined at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |alphaglosined at gmail.com

--- Comment #2 from Richard Cattermole <alphaglosined at gmail.com> ---
A more substantial example of why this is a problem:

---
import std.stdio;
import std.algorithm;

struct A {
    this(int i) { id=counter++; counterLive[id] = 1; writeln("CTOR ", id); }
    ~this() { counterLive[id]--; writeln("DTOR ", id); }
    this(this) { counterLive[id]++;writeln("POSTBLIT ", id); }

    static size_t counter=1;
    static size_t[size_t] counterLive;
    size_t id;
}

void main() {
    foreach(ref r; [A(10), A(2), A(3)].map!(x => x)) { }

    foreach(k, v; A.counterLive)
        if (v > 0) writeln("A (", k, ") count ", v);
}
---

Output:

---
CTOR 1
CTOR 2
CTOR 3
POSTBLIT 1
POSTBLIT 1
DTOR 1
POSTBLIT 2
POSTBLIT 2
DTOR 2
POSTBLIT 3
POSTBLIT 3
DTOR 3
A (2) count 2
A (3) count 2
A (1) count 2
DTOR 3
DTOR 2
DTOR 1
---

The destructors for 3 copies never get called.

--


More information about the Digitalmars-d-bugs mailing list