copy and array length vs capacity. (Doc suggestion?)

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 22:29:12 PST 2015


On Sunday, November 22, 2015 03:19:54 Jon D via Digitalmars-d-learn wrote:
> On Sunday, 22 November 2015 at 00:31:53 UTC, Jonathan M Davis
> wrote:
> >
> > Honestly, arrays suck as output ranges. They don't get appended
> > to; they get filled, and for better or worse, the documentation
> > for copy is probably assuming that you know that. If you want
> > your array to be appended to when using it as an output range,
> > then you need to use std.array.Appender.
> >
> Hi Jonathan, thanks for the reply and the info about
> std.array.Appender. I was actually using copy to fill an array,
> not append. However, I also wanted to preallocate the space. And,
> since I'm mainly trying to understand the language, I was also
> trying to figure out the difference between these two forms of
> creating a dynamic array with an initial size:
>
>     auto x = new int[](n);
>     int[] y;  y.reserve(n);
>
> The obvious difference is that first initializes n values, the
> second form does not. I'm still unclear if there are other
> material differences, or when one might be preferred over the
> other :) It's was in this context the behavior of copy surprised
> me, that it wouldn't operate on the second form without first
> filling in the elements. If this seems unclear, I can provide a
> slightly longer sample showing what I was doing.

If you haven't read this article yet, then you should read it:

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

It doesn't use the official terminology (in particular, it talks about T[]
as being a slice and the underlying GC buffer as being the dynamic array,
whereas per the language spec T[] is the dynamic array (which is alsa a
slice of some sort of memory), and the underlying GC buffer that typically
backs a dynamic array is just a GC buffer and is essentially an
implementation detail), but it should give you good insight into how arrays
work in D.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list