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

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Nov 10 21:34:15 UTC 2024


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

Walter Bright <bugzilla at digitalmars.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |bugzilla at digitalmars.com

--- Comment #7 from Walter Bright <bugzilla at digitalmars.com> ---
Let's rewrite:

  class MyClass
  {
    void doSomething();

    void myMethod() @nogc
    {
        acceptsCallback((){ doSomething(); });
    }
  }

to make visible what is happening.

  class MyClass
  {
    void doSomething(MyClass this);

    void myMethod(MyClass this) @nogc
    {
        auto outer = &this;
        void func(MyClass* outer)
        {
            doSomething(*outer);
        }
        acceptsCallback(&outer.func);
    }
  }

func is a member of myMethod, not a member of MyClass. func's "this" pointer is
a reference to the stack frame of myMethod, not a reference to MyClass.
acceptsCallback() is allowed to squirrel away the address of func(), and could
access it after myMethod() has exited. This will result in corrupted memory.

The solution is for acceptsCallback to annotate its parameter with `scope`,
which says it will not preserve its argument past the lifetime of
acceptsCallback.

--


More information about the Digitalmars-d-bugs mailing list