new T[size] vs .reserve

Maxim Fomin maxim at maxim-fomin.ru
Sat Feb 2 09:24:00 PST 2013


On Saturday, 2 February 2013 at 16:36:29 UTC, Namespace wrote:
> Currently something like new ubyte[4]; reserves space for _at 
> least_ 4 items.
> But if I want to store now something, the index isn't 0, it's 4.
> Let me explain that on a brief example:
>
> [code]
> import std.stdio;
>
> void main() {
> 	ubyte[] arr = new ubyte[4];

You asked for array with four zeros (T.init for ubyte is 0).

> 	arr ~= 4; // desirable: [4, 0, 0, 0];
> 	writeln(arr); // prints: [0, 0, 0, 0, 4]

You got it. And you appended 4 to them, so you got proper result.
  	
> 	ubyte[] arr2;

You asked for empty array.

> 	arr2.reserve(4);
> 	arr2 ~= 4; // expect: [4, 0, 0, 0];
> 	writeln(arr2); // prints: [4] just as well
> }

You appended 4 to empty array and you got [4]. By the way, note 
that the output is not [4,0,0,0] it is [4] since no one has 
pushed three zeros there.

> [/code]
>
> So is there any reason why this behaviour is like it is?

I found it is consistent and complying yo spec. new ubyte[4] and 
reverse(4) do different things.

> As I looked at arr.length and arr.capacity for the first time I 
> was schocked: I want only space for 4 items, but I got space 
> for 15.
> I read in the docs that .reserve extends the space to at least 
> SIZE items, but maybe more. But at that time and still yet I 
> found nothing about new ubyte[SIZE]. So I ask:
> wouldn't it be better, if new ubyte[4] reserves only space for 
> 4 items and reallocs only if I append more than 4?

Since you have two tools which do different things, you can 
select that tool which does what you wanted. What's the problem 
here?


More information about the Digitalmars-d-learn mailing list