closures

Jarrett Billingsley jarrett.billingsley at gmail.com
Thu Jul 16 08:24:04 PDT 2009


On Thu, Jul 16, 2009 at 8:02 AM, Jens<jens-theisen-tmp01 at gmx.de> wrote:
> Hello there,
>
> I'm new to D and experimenting with closures. I know the basics of how compilers translate things, especially in C++. So I appreciate the difficulty of implementing closures correctly and been wondering if it really works. I found a place where dmd 2 appears to fail, but I don't know whether that's a bug or just not supported:
>
> import std.stdio;
>
> struct Foo
> {
>  int a = 7;
>  int bar() { return a; }
>
>  int delegate() makedelegate() {
>    int abc() { return a; }
>    return &abc;
>  }
> }
>
> void call(int delegate() dg)
> {
>  writefln("foo: %d", dg());
> }
>
> int delegate() makedelegate1()
> {
>  int x = 27;
>  int abc() { return x; }
>  return &abc;
> }
>
> int delegate() makedelegate2()
> {
>  Foo f;
>  int abc() { return f.a; }
>  return &abc;
> }
>
> int delegate() makedelegate3()
> {
>  Foo f;
>  return &f.bar;
> }
>
> int delegate() makedelegate4b(ref Foo f)
> {
>  int abc() { return f.a; }
>  return &abc;
> }
>
> int delegate() makedelegate4()
> {
>  Foo f;
>  return makedelegate4b(f);
> }
>
>
> void main(string[] args)
> {
>  // On dmd v2.029, linux build, this...
>
>  call(makedelegate1()); // ...works: 27
>  call(makedelegate2()); // ...works: 7
>  call(makedelegate3()); // ...doesn't work: 134518855
>  call(makedelegate4()); // ...doesn't work: 134518947
>
>  Foo f;
>  call(&f.bar); // ...works: 7
> }
>
> In case 4 the reference is explicit, so it's somehow easier to see that something dangerous is being done, but in case 3, D seems to make it too easy to shoot yourself in the foot.
>
> Is there a resource discussing these issues?

Yeah, you've found it :)

I think what's going on here is that the compiler will *only* allocate
closures for nested functions.  However allocating a closure for a
delegate of a value object would be a nice addition.


More information about the Digitalmars-d-learn mailing list