Why are static arrays not ranges?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 21 15:48:23 PDT 2015


On Monday, September 21, 2015 20:46:51 Jack Stouffer via Digitalmars-d-learn wrote:
> On Monday, 21 September 2015 at 20:39:55 UTC, Jesse Phillips
> wrote:
> > A static array has a constant length, so it is not possible to
> > popFront on a static array.
> >
> > Making a dynamic array from it is easy, just slice it with []:
> >
> >      pragma(msg, isInputRange!(typeof(a[])));
> >      pragma(msg, isForwardRange!(typeof(a[])));
> >      pragma(msg, isRandomAccessRange!(typeof(a[])));
>
> Thanks for all of the replies. I was under the impression that
> the slicer allocated GC, but some tests show that's not true.

All that slicing a static array does is give you a dynamic array which
refers to the static array. It's then the same as any other dynamic array
except that you have to make sure that it doesn't continue to refer to the
static array after the static array no longer exists, and it's guaranteed to
have no extra capacity, so if you do append to it, it's guaranteed to
reallocate, whereas one allocated via new may or may not have extra
capacity, depending on what's been done with that dynamic array and any
other dynamic arrays were sliced from it and thus may or may not have to be
reallocated when it's appended to. Similarly, slicing malloced memory gets
you a dynamic array which refers to malloced memory and thus has no extra
capacity, and you have to be careful to not still have it around when the
malloced memory is freed.

I would suggest that you read this

http://dlang.org/d-array-article.html

and possibly watch this

http://dconf.org/2015/talks/davis.html

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list