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.

There is, but it isn't pretty.

import std.stdio;

void main()
{
int i = 1;
int* n = null;
auto dg = (){ if (n is null) n = cast(int*)i; else writefln("%s", n); }; dg();
i = 2;
dg(); // prints '1'
}


1. I'm pretty sure that D creates the delegate "lazily" in the sense that the first call is what captures the variable. Hence, we must call it where we want to capture, not after the change occurs.

2. We use a temp local variable to act as a place holder. A singleton basically.

You might be able to wrap this up in some type of template that makes it easier to use but it does work.


Reply via email to