On 10.10.2011 08:58, Gor Gyolchanyan wrote:
There is a huge difference between a static and a dynamic array.
Dynamic array is an indirected type (objects of that type are pointers
to the actual data), while static arrays are PODs (directly refers to
the data).
Dynamic arrays are always size_t.sizeof * 2 bytes long, while static
arrays are typeof(T[0]).sizeof * T.length bytes long. That makes
static arrays expensive to move around. Making the array literals
static by default would mean unnecessary copying most of the time. In
those few cases, where it is necessary, you can explicitly make them
static arrays.

If they'd been made immutable, the way they should be, this wouldn't be an issue. The efficiency argument is bogus, I think. Because they're mutable, they always have to be created on the heap. So by default, they are very slow.


Cheers,
Gor.

On Mon, Oct 10, 2011 at 10:42 AM, Norbert Nemec<[email protected]>  wrote:
Hi there,

after a very busy and eventful year in my personal life, I have now
finally found some time to play with D2. I am very impressed by the
progress!

One thing I noticed was that static arrays are somehow strangely limited:

It is possible to overload based on the length:

--------
void f(int[3] x) {
   writeln("int[3]: ",x);
}

void f(int[4] x) {
   writeln("int[4]: ",x);
}

int main(string argv[]) {
   f([1,2,3]);
   f([1,2,3,4]);
   return 0;
}
--------

However, used as function template argument, a static array is casted to
a dynamic array:

-----------
void g(T)(T x) {
   static assert (__traits(isStaticArray,T));
   enum N = T.init.length;
   writeln(N,": ",x);
}

int main(string argv[]) {
   g([1,2,3]);
   return 0;
}
------------

gives the error message:

|  Error: static assert  (__traits(isStaticArray,int[])) is false
|         instantiated from here: g!(int[])

Without the assertion, N is defined to 0.

Further investigation shows:

-------
        g!(int[3])([1,2,3]);  // passes a static array
-------
        int[3] x3 = [1,2,3];
        g(x3);                // passes a static array
-------
        auto z3 = [1,2,3];    // defines z3 as dynamic array
        g(y3);                // passes a dynamic array
-------

So it seems, the problem is that array literals on their own turned into
dynamic arrays unless you explicitly state a static array type in some way.

Wouldn't it make more sense the other way around? After all, turning a
static array into a dynamic array is easy, the other way around is
prohibited by the compiler. If array literals simply had a static array
type, they could be implicitly casted to dynamic arrays when necessary
but stay static if possible.

Greetings,
Norbert


Reply via email to