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

Jon D via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 15:34:25 PST 2015


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.


More information about the Digitalmars-d-learn mailing list