Nasty corner case behaviour

Suleyman sahmi.soulaimane at gmail.com
Fri Apr 19 22:17:08 UTC 2019


On Thursday, 18 April 2019 at 05:01:17 UTC, H. S. Teoh wrote:
> ...

Sneaky enough.
The problem is the value copy semantics of S which results in an 
address to a dead stack frame being saved.
If you make it a ref parameter the issue goes away.

    import std.algorithm : filter, map;
    import std.stdio;

    struct S {
        bool flag;
        auto method() {
            return [ 1 ].filter!(e => flag);
        }
    }

    void main() {
        auto s = S(true);
        writeln(s.method);

        auto arr = [ s ];
        writeln(arr[0].method);

        auto mappedArray = arr.map!((ref e) => e.method);
        writeln(mappedArray.front);
        writeln(mappedArray);
    }

  Output:

    [1]
    [1]
    [1]
    [[1]]



More information about the Digitalmars-d mailing list