new T[size] vs .reserve

Namespace rswhite4 at googlemail.com
Sat Feb 2 08:36:28 PST 2013


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];
	arr ~= 4; // desirable: [4, 0, 0, 0];
	writeln(arr); // prints: [0, 0, 0, 0, 4]
	
	ubyte[] arr2;
	arr2.reserve(4);
	arr2 ~= 4; // expect: [4, 0, 0, 0];
	writeln(arr2); // prints: [4] just as well
}
[/code]

So is there any reason why this behaviour is like it is?

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?


More information about the Digitalmars-d-learn mailing list