dynamic array .length vs .reserve - what's the difference?
bachmeier
no at spam.net
Thu Jul 30 17:59:48 UTC 2020
On Thursday, 30 July 2020 at 15:58:28 UTC, wjoe wrote:
> 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.
Here's a simple example to see that reserve and length serve
different purposes. In particular, reserve doesn't fill any
elements but allocates enough memory, while setting length puts
values into the elements:
import std.stdio;
void main() {
double[] x;
writeln(x.length);
writeln(x.capacity);
x.reserve(50);
writeln(x.length);
writeln(x.capacity);
x ~= 1.5;
writeln(x);
double[] y;
y.length = 50;
writeln(y.length);
writeln(y.capacity);
y ~= 1.5;
writeln(y);
}
https://run.dlang.io/is/1EWf5R
More information about the Digitalmars-d-learn
mailing list