On Wednesday, 28 May 2014 at 02:05:43 UTC, Meta wrote:
On Tuesday, 27 May 2014 at 23:18:12 UTC, Idan Arye wrote:
Well, it won't work for the example that opened this
thread(converted to use lambdas).
As for limiting the delegate version to ones that use @pure
and @nogc, take another look at my example. The lambdas don't
allocate anything so they're obviously @nogc. As for @pure,
they doesn't have any side effects, and depend only on their
arguments(they don't have arguments, and they are constant
functions) and their scope(which happens to be mutable, but
you could easily make it immutable and nothing will change).
Delegates by default allocate a closure. If they're marked
@nogc, they'd be unable to allocate that closure... I think.
The pure annotation is to stop them from accessing global
mutable state.
From what I know(don't know how it is implemented in D. I know it
doesn't work that way in languages that emulate closures like C++
and Java) delegates don't "allocate a closure" - rather, they use
a the callstack frame that was already allocated by the function
as a closure. While it's true that they have to save a reference
to that frame, there is no separately GCed memory for saving that
reference - it's stored in the fat pointer together with the
function pointer.
Either this or that - it doesn't affect @nogc. @nogc means that
when you *run* the function no GCed memory is allocated. Whatever
memory allocated for the closure(and the function pointer! which
regular `function`s also have!) is allocated when you *create*
the delegate.
The lambdas in my example don't allocate any memory when you
*run* them.
Any lambda - with or without closure - needs to allocate memory
when you *create* it.
At any rate, a delegate without a closure is either a
`function`(which can be body-hashed without any problem) or a
method(which doesn't need body-hashing), so having the @nogc
restriction would be pointless even if @nogc prevented closures.
And when I think about it, I also fail to understand why you
suggest the @pure restriction - the problem in body-hashing is
what the identifier refer to, not what the lambda does with it...