www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 21745] New: Closure created in struct constructor passed to


          Issue ID: 21745
           Summary: Closure created in struct constructor passed to class
                    constructor is not heap allocated
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: default_357-line yahoo.de

Despite clearly escaping, a delegate created in a struct constructor and passed
to a class constructor is allocated on the heap.

Consider a class:

class Bar
    int delegate() dg;
    this(int delegate() dg) { this.dg = dg; }

And a struct:

struct Foo
    int i;
    Bar bar;
    this(int i)
        this.i = i;
        this.bar = new Bar({ return this.i; });

And a helper function, just to ensure that the variable gets a deterministic
location on the stack:

Foo getFoo(int i) { return Foo(i); }

Then when we

void main() {
  auto foo = getFoo(5);
  assert(foo.bar.dg() == 5);

We see that dg returns 6, despite belonging to the constructor where i was 5.

Mar 21 2021