On Thursday, 9 June 2016 at 22:06:24 UTC, Mathias Lang wrote:
To avoid the delegate being GC allocated, use `scope foo = (int i) { ... }`
at call site.
You can also make your function signature as `void func(scope void delegate() dg)` in which case it won't allocate if you pass a literal
directly.

2016-06-09 23:57 GMT+02:00 maik klein via Digitalmars-d < [email protected]>:

On Thursday, 9 June 2016 at 21:32:33 UTC, Alex Parrill wrote:

On Thursday, 9 June 2016 at 21:02:26 UTC, maik klein wrote:

Has this been done before?


Well, yes, the entire point of delegates is to be able to capture variables (as opposed to function pointers, which cannot).


auto createADelegate(int captured) {
        return (int a) => captured + a;
}

void main() {
        auto dg1 = createADelegate(5);
        auto dg2 = createADelegate(32);
        assert(dg1(5) == 10);
        assert(dg1(10) == 15);
        assert(dg2(8) == 40);
        assert(dg2(32) == 64);
}

https://dpaste.dzfl.pl/90ebc29651f6

(Unfortunately template delegates, like the ones used with map, don't keep their captured variables alive after the captured variables go out of scope, but it doesn't sound like you need those)


I meant, "has this been implement as a library before". I am well aware that delegates exist in the language but as far as I know you can not do manual allocation with delegates (to avoid the GC).

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?

Also scope on local vars is marked to be deprecated, see http://stackoverflow.com/a/4713064/944430

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.

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.




Reply via email to