Variables with scoped destruction in closures

Nordlöw via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 14 09:37:06 PDT 2016


On Friday, 14 October 2016 at 14:00:53 UTC, ag0aep6g wrote:
> As for ways to make this work:
>
> 1) You can move s to the heap yourself:
>
> ----
> auto below3(size_t n, S s = S.init)
> {
>     import std.algorithm.mutation: moveEmplace;
>     auto onHeap = cast(S*) new ubyte[S.sizeof];
>     moveEmplace(s, *onHeap);
>         /* If there's a function that does allocation and 
> moveEmplace
>         in one go, I can't find it. */
>     return 0.iota(n).filter!(_ => _ < *onHeap);
> }
> ----
>
> 2) Or you can move it into a struct that gets returned (more 
> involved):
>
> ----
> auto below4(size_t n, S s = S.init)
> {
>     static struct Below4CustomFilter(R)
>     {
>         R range;
>         S s;
>
>         this(R range, S s)
>         {
>             this.range = range;
>             this.s = s.move();
>             skipFiltered();
>         }
>
>         private void skipFiltered()
>         {
>             while (!range.empty && range.front >= s.value)
>                 range.popFront();
>         }
>
>         @property bool empty() { return range.empty; }
>         @property auto front() { return range.front; }
>         void popFront() { range.popFront(); skipFiltered(); }
>         /* ... more advanced range primitives ... */
>     }
>     static customFilter(R)(R range, S s)
>     {
>         return Below4CustomFilter!R(range, s.move());
>     }
>     return customFilter(0.iota(n), s.move());
> }
> ----

I'm not interested in either of these solutions.

The whole idea in the first place was to avoid extra (GC) heap 
allocations together with reusing existing Phobos ranges in a 
functional way.

If I remove the explicit dtor from `S` the code compiles. Can 
somebody please explain why? Walter?

Thanks, anyway.

I guess I have to fix the compiler myself :)


More information about the Digitalmars-d-learn mailing list