[Issue 24838] New: @nogc lambda shouldn't allocate closure when lambda refers only to 'this'

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Oct 30 15:11:42 UTC 2024


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

          Issue ID: 24838
           Summary: @nogc lambda shouldn't allocate closure when lambda
                    refers only to 'this'
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: turkeyman at gmail.com

error : function `MyClass.myMethod` is `@nogc` yet allocates closure for
`myMethod()` with the GC
       delegate `MyClass.myMethod.__lambda3` closes over variable `this`

class MyClass
{
    void doSomething();

    void myMethod() @nogc
    {
        acceptsCallback(&notLambda);  // this works; delegate is created from
the method
        acceptsCallback((){ doSomething(); }); // doesn't work! closure
needlessly tries to allocate
    }

    void notLambda()
    {
      doSomething();
    }
}


I think this is essentially a bug and a serious usability hindrance.

The lambda seems to try and allocate a closure because it captures `this`, but
that's no reason to allocate a closure!
A function that receives `this` as context is called a method... in the
extremely common case where a lambda closes `this` and nothing else, the lambda
should just be synthesised as a method of `this` rather than a closure. The
double-indirection from the closure is pointless and inefficient anyway.

This would make lambda's about 100x more useful in @nogc code, because they can
naturally access `this` as context without any closure allocation.

--


More information about the Digitalmars-d-bugs mailing list