[Issue 2043] Closure outer variables in nested blocks are not allocated/instantiated correctly: should have multiple instances but only have one.

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Apr 5 22:47:17 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=2043

--- Comment #36 from timon.gehr at gmx.ch ---
(In reply to Walter Bright from comment #35)
> 1. alloca() won't work, because that won't survive the end of the function.
> ...

As I said, just do it if the delegate does not escape.

> 2. Doing a heap alloc/free for every loop iteration is expensive, and since
> the cost is hidden it will come as a nasty surprise.
> ...

I don't get how this is different from other implicit heap closure allocations.
A function that does such an implicit allocation not within a loop in its own
body might well be called in a loop and cause a performance bottleneck.
Profile.

> 3. Doing a gc allocation will generate an unbounded set of allocations, also
> coming as a nasty surprise.
> ...

This is true for all implicit heap allocations. They are also often convenient
and there are already ways to flag them.

> 4. Doing my delegate rewrite will cause a "by value" which changes the
> semantics, so that won't work.
> ...

That's not true. It just gets rid of the memory corruption. The capture is
still by reference, which you can easily verify by creating more than one
closure over the same instance of the variable. This is the standard semantics
for this kind of thing. The delegate rewrite is a very hacky way to implement
it though, and probably not really the most convenient as you need to thread
through control flow and the generated code will not be as good as it could be.

> I suspect the pragmatic solution is to disallow the capture of loop
> variables by reference by escaping delegates. The user then will be notified
> of the problem, and he can construct an efficient workaround that works for
> his application.

This fixes the memory corruption issue without much work. Deprecation might be
necessary even if we fix this the right way in the end, so this is a good first
step.

--


More information about the Digitalmars-d-bugs mailing list