Remove closure allocation
Neia Neutuladh
neia at ikeran.org
Sat May 26 18:10:30 UTC 2018
On Saturday, 26 May 2018 at 15:00:40 UTC, Malte wrote:
> This compiles with DMD, however it returns random numbers
> instead of the value I passed in. Looks like a bug to me.
> Should that work or is there any other pattern I could use for
> that?
Filed as https://issues.dlang.org/show_bug.cgi?id=18910
As for the larger issue, you have to store `q` somewhere.
The compiler could store it on the stack, but the compiler would
have to do a lot of work to prove that that's safe -- that the
return value from `arr.map` doesn't escape the current function,
that `map` doesn't save the thing you passed to it anywhere, that
sort of thing.
And that sort of analysis is flaky. It's a recipe for code that
compiles on one version of a compiler and not the next, a lot of
bug reports that are hard to track down, that sort of thing. And
it means that it has to assume the worst for functions that it
doesn't have the source for -- when you pass a delegate, when you
call an extern(D) function, when you call a virtual method.
So the compiler does the safe thing, and it has the GC allocate a
bit of memory to hold `q`.
The way around that is the `scope` keyword. The compiler can do
that complex analysis one function at a time; that's sufficiently
simple. So if you wrote a `map` function, you could define it as
taking a `scope U delegate(T)` and the compiler wouldn't need to
use the GC there.
That obviously adds restrictions on how you can write that
function.
More information about the Digitalmars-d-learn
mailing list