Allocate N elements

bearophile bearophileHUGS at lycos.com
Mon Jul 15 06:13:41 PDT 2013


Namespace:

> void main()
> {
> 	int[] arr1 = new int[512];
> 	writeln(arr1.length, "::", arr1.capacity);
> 	int[] arr2 = new int[](512);
> 	writeln(arr2.length, "::", arr2.capacity);
> }
> ----
>
> Output:
> 512::1019
> 512::1019

import std.stdio, std.array;
void main() {
     auto a1 = new int[512];
     writeln(a1.length, " ", a1.capacity);
     auto a2 = new int[](512);
     writeln(a2.length, " ", a2.capacity);
     auto a3 = minimallyInitializedArray!(int[])(512);
     writeln(a3.length, " ", a3.capacity);
}


Output:
512 1019
512 1019
512 0

But that (of new arrays) is a bad design, it wastes too much 
memory, and I think it should be fixed. In Python this doesn't 
overallocate:

a4 = [0] * 512

An alternative is to introduce a function like 
std.array.InitializedArray.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list