Why does reverse also flips my other dynamic array?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 12 14:59:23 PDT 2015


On 09/12/2015 02:29 PM, Marco Leise wrote:

 > Note that often the original dynamic array has additional
 > capacity beyond its length. This can be used to ~= additional
 > items without causing a reallocation, but is lost when you
 > do the assignment "b = a".

Actually, the capacity is still there, useful to the runtime. 
Interestingly, the first dynamic array that is appended the new element 
becomes the owner of that capacity. The capacity of the other dynamic 
array becomes 0.

import std.stdio;

void main(){

   int [] a = [1,2,3,4,5];
   int [] b = a;

   writeln(a.ptr, " ", b.ptr);
   writeln(a.capacity, " ", b.capacity);
   a ~= 42;    // <-- change to b, now b owns the capacity
   writeln(a.ptr, " ", b.ptr);
   writeln(a.capacity, " ", b.capacity);
}

Ali



More information about the Digitalmars-d-learn mailing list