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

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 16:31:35 PST 2015


On Saturday, November 21, 2015 23:34:25 Jon D via Digitalmars-d-learn wrote:
> Something I found confusing was the relationship between array
> capacity and copy(). A short example:
>
> void main()
> {
>      import std.algorithm: copy;
>
>      auto a = new int[](3);
>      assert(a.length == 3);
>      [1, 2, 3].copy(a);     // Okay
>
>      int[] b;
>      b.reserve(3);
>      assert(b.capacity >= 3);
>      assert(b.length == 0);
>      [1, 2, 3].copy(b);     // Error
> }
>
> I had expected that copy() would work if the target had
> sufficient capacity, but that's not the case. Target has to have
> sufficient length.
>
> If I've understood this correctly, a small change to the
> documentation for copy() might make this clearer. In particular,
> the "precondition" section:
>
>      Preconditions:
>      target shall have enough room to accomodate the entirety of
> source.
>
> Clarifying that "enough room" means 'length' rather than
> 'capacity' might be beneficial.

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.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list