--- Comment #27 from Walter Bright <> ---
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

  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();
    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.


Reply via email to