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

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 23 07:19:08 PST 2015


On 11/21/15 10:19 PM, Jon D 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);

If you want to change the size of the array, use length:

y.length = n;

This will extend y to the correct length, automatically reserving a 
block of data that can hold it, and allow you to write to the array.

All reserve does is to make sure there is enough space so you can append 
that much data to it. It is not relevant to your use case.

> 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.

extending length affects the given array, extending if necessary. 
reserve is ONLY relevant if you are using appending (arr ~= x). It 
doesn't actually affect the "slice" or the variable you are using, at 
all (except to possibly point it at newly allocated space).

copy uses an "output range" as it's destination. The output range 
supports taking elements and putting them somewhere. In the case of a 
simple array, putting them somewhere means assigning to the first 
element, and then moving to the next one.

-Steve


More information about the Digitalmars-d-learn mailing list