dynamic array .length vs .reserve - what's the difference?

wjoe invalid at example.com
Thu Jul 30 15:58:28 UTC 2020


I just stumbled upon code like this:

struct Foo(T)
{
     T[] b;

     this(int n)
     {
         b.reserve(n);
         b.length = n;
     }
}

.reserve looks redundant.

The docs are explaining .length nicely, however lack any 
specifics about reserve.

Changing the length of an array may relocate and copy. New items 
are initialized with T.init - is that true for both length and 
reserve ?

Also there's .capacity - is that equivalent to reserve ?

Another curiosity I noticed is that the docs say that the runtime 
tries to resize in place, however:

b = b[0..$-1]; if length==1 seems to collect the memory at once 
because if it's immediately followed by b.length = 1; or b ~= 
someT; b.ptr points to a new address.
Why ?

I know that b=b[0..0]; is equivalent to b = null; but I still 
don't understand the need for a new allocation when b could be 
resized in place.
How can I hold on to the memory originally reserved by b but at 
the same time allow the array to temporarily be empty?


More information about the Digitalmars-d-learn mailing list