I implemented delegates in D

Mathias Lang via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 9 17:23:13 PDT 2016


2016-06-10 1:20 GMT+02:00 maik klein via Digitalmars-d <
digitalmars-d at puremagic.com>:

> But that means that the closure will be allocated on the stack right? What
> happens when I send it with
> http://dpldocs.info/experimental-docs/std.concurrency.send.html
>
> Will it copy the function or will it only send the pointer?
>

Yes it will be stack allocated.
But if you wish to `send` something, I think you're better off using a
function in an object (disclaimer: never tried).
Functions are not copied, so I guess you are refering to the context
pointer ?


> Also scope on local vars is marked to be deprecated, see
> http://stackoverflow.com/a/4713064/944430
>
>
Yeah and they are not going away anytime soon. There's a reason why the
compiler won't even warn about them. They are extremely useful and there is
currently no replacement for them.


> I don't think that I can use delegates (without the gc), what I basically
> do is send a delegate to a thread, create a fiber on that thread and put it
> in a thread local array.
>

Did you try to send a native delegate ? I would be very surprised if you
were allowed to do so.


> The delegate contains a "future" that I can access on a different thread.
> I use it as mechanism to share results. (Its synchronized with atomics)
>
> I mean currently I just use gc delegates, but I am exploring some
> alternatives.
>
>
Note that not all delegates allocate. Function local delegate refering to
variable do, but the one refering to aggregate never do.

E.g. the following compiles and run:

```
struct Foobar { string toString() @nogc { return "Foobar"; } }

void func (string delegate() ts) @nogc {}
void main () @nogc
{
    scope c = new Object;
    Foobar s;
    func(&c.toString); // ptr=c funcptr=toString
    func(&s.toString); //ptr =s funcptr=toString

    string delegate() @nogc dg;
    dg.funcptr = (&s.toString).funcptr; // There might be a better way to
do that
    dg.ptr  = &s;
    assert("Foobar" == dg());
}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20160610/a52e87e6/attachment.html>


More information about the Digitalmars-d mailing list