Creating 1000 instances

Simen Kjærås simen.kjaras at gmail.com
Fri Feb 19 14:56:50 UTC 2021


On Friday, 19 February 2021 at 10:02:05 UTC, Siemargl wrote:
> On Friday, 19 February 2021 at 08:29:36 UTC, Ferhat Kurtulmuş 
> wrote:
>
>> Since classes are reference types all instances of files will 
>> be the same reference of "new File()", which you probably 
>> don't want.
>
> Is any differences between x and y definitions?
>
> MyClass [] x, y;
> x = new MyClass[7];
>
> y= new MyClass[](8);

The only part of the documentation I've found that talks about 
this is here:
https://dlang.org/spec/expression.html#new_expressions

The main difference I know of comes with multidimensional arrays:

     auto a = new int[4][4];
     pragma(msg, typeof(a)); // Prints int[4][]
     auto b = new int[][](4,4);
     pragma(msg, typeof(b)); // Prints int[][]

Since the former is a dynamic array of static arrays, the first 
size parameter cannot be passed at runtime:

     auto n = 4;
     // Error: variable n cannot be read at compile time
     auto c = new int[n][n];

But must be a compiletime constant:

     enum N = 4;
     auto d = new int[N][n];
     pragma(msg, typeof(d)); // Prints int[4][]

The other syntax however, can take runtime values, but does not 
encode the size in the type:

     auto e = new int[][](n,n);
     pragma(msg, typeof(e)); // Prints int[][]

The other big thing about the []() syntax is it actually 
initializes the arrays of arrays for you:

     assert(e[0].length == n);

If you were to use new int[][n], you would need to initialize 
each array of arrays manually:

     auto f = new int[][n];
     assert(f[0].length == 0); // it's empty
     foreach (i; 0..n) {
         f[i] = new int[n]; // Have to do this yourself.
     }

--
   Simen


More information about the Digitalmars-d-learn mailing list