www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Diff between function and delegate

reply "Smoke" Adams <SA2432 gmail.com> writes:
I have

alias fnc = void function(Object);
alias del = void delegate();

Does func avoid the GC? I am passing in this to Object so I don't 
technically need a delegate or a "context". I want to be sure 
that I'm actually gaining something here by doing this.

I read somewhere that delegates only require the GC when they use 
objects outside their scope. Do delegates always use the GC or 
only in certain cases?
Jun 27 2016
parent reply Mathias Lang <mathias.lang sociomantic.com> writes:
On Monday, 27 June 2016 at 19:34:06 UTC, "Smoke" Adams wrote:
 I have

 alias fnc = void function(Object);
 alias del = void delegate();

 Does func avoid the GC? I am passing in this to Object so I 
 don't technically need a delegate or a "context". I want to be 
 sure that I'm actually gaining something here by doing this.

 I read somewhere that delegates only require the GC when they 
 use objects outside their scope. Do delegates always use the GC 
 or only in certain cases?
Delegate don't GC allocate when: - You take a pointer to a member function - The function accept a `scope` delegate and you pass a literal - You use `scope myDG = (Params) { body... }`
Jun 27 2016
next sibling parent Meta <jared771 gmail.com> writes:
On Monday, 27 June 2016 at 19:59:05 UTC, Mathias Lang wrote:
 - You use `scope myDG = (Params) { body... }`
It looks like i is still moved to the heap but marking `test` with nogc compiles successfully. Then when I run the code the assertion is triggered. What exactly is going on here? auto test() nogc //Compiles { int i = 10; scope dg = { assert(i == 10); }; //AssertFailure i = 11; return dg; } void main() { auto dg = test(); dg(); }
Jun 29 2016
prev sibling parent jmh530 <john.michael.hall gmail.com> writes:
On Monday, 27 June 2016 at 19:59:05 UTC, Mathias Lang wrote:
 Delegate don't GC allocate when:
 - You take a pointer to a member function
 - The function accept a `scope` delegate and you pass a literal
 - You use `scope myDG = (Params) { body... }`
I have a somewhat related question. Why use a delegate for a closure if you can restructure the function to use partial (from std.functional) instead? The delegate will use GC, but I don't think partial would (but not entirely sure).
Jun 29 2016