[Issue 2043] Closure outer variables in nested blocks are not allocated/instantiated correctly: should have multiple instances but only have one.

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Apr 5 06:07:18 UTC 2018


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

--- Comment #27 from Walter Bright <bugzilla at digitalmars.com> ---
D closures are "by reference" rather than "by value". I make use of it being by
reference all the time, as well as it being much more efficient. Changing it
would likely break all sorts of code. So then the question is, what to do if
you want it by value?

One solution to creating such a delegate is to create it inside a nested
function:

  import core.stdc.stdio;
  int main()
  {
    foreach (i; 0 .. 2)
    {
        void delegate(int) nested()
        {
            auto myi = i; // capture current value of i for use by del()
            void del(int x)  // the real delegate
            {
                printf("&myi = %p\n", &myi);
            }
            return &del;
        }
        auto dg = nested();
        dg(1);
    }
    return 0;
  }

Running it:
  &myi = 00261014
  &myi = 00261024

This works because `del` escapes its scope, and so the compiler allocates a
closure each time nested() is called, and `myi` is captured in that closure.

Now, the compiler could actually rewrite the delegate into the nested form
above, but as I said, this changes the semantics of existing code, as well as
being pretty inefficient. I doubt it would be acceptable.

--


More information about the Digitalmars-d-bugs mailing list