On Monday, 23 November 2015 at 15:19:08 UTC, Steven Schveighoffer wrote:
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

Thanks for the reply. And for your article (which Jonathan recommended). It clarified a number of things.

In the example I gave, what I was really wondering was if there is a difference between allocating with 'new' or with 'reserve', or with 'length', for that matter. That is, is there a material difference between:

    auto x = new int[](n);
    int[] y; y.length = n;

I can imagine that the first might be faster, but otherwise there appears no difference. As the article stresses, the question is the ownership model. If I'm understanding, both cause an allocation into the runtime managed heap.

--Jon

Reply via email to