On Saturday, 5 August 2017 at 18:22:38 UTC, Stefan Koch wrote:
On Saturday, 5 August 2017 at 18:19:05 UTC, Stefan Koch wrote:
On Saturday, 5 August 2017 at 18:17:49 UTC, Simon Bürger wrote:
If a lambda function uses a local variable, that variable is captured using a hidden this-pointer. But this capturing is always by reference. Example:

    int i = 1;
    auto dg = (){ writefln("%s", i); };
    i = 2;
    dg(); // prints '2'

Is there a way to make the delegate "capture by value" so that the call prints '1'?

Note that in C++, both variants are available using
  [&]() { printf("%d", i); }
and
   [=]() { printf("%d", i); }
respectively.

No currently there is not.

and it'd be rather useless I guess.
You want i to be whatever the context i is a the point where you call the delegate.
Not at the point where you define the delegate.

No, sometimes I want i to be the value it has at the time the delegate was defined. My actual usecase was more like this:

        void delegate()[3] dgs;
        for(int i = 0; i < 3; ++i)
                dgs[i] = (){writefln("%s", i); };


And I want three different delegates, not three times the same. I tried the following:

        void delegate()[3] dgs;
        for(int i = 0; i < 3; ++i)
        {
                int j = i;
                dgs[i] = (){writefln("%s", j); };
        }

I thought that 'j' should be considered a new variable each time around, but sadly it doesn't work.

Reply via email to