Inability to dup/~ for const arrays of class objects

Ali Çehreli acehreli at yahoo.com
Thu May 30 00:57:40 PDT 2013


On 05/30/2013 12:11 AM, Maxim Fomin wrote:

 > On Thursday, 30 May 2013 at 06:12:03 UTC, Ali Çehreli wrote:
 >> On 05/29/2013 10:54 PM, Maxim Fomin wrote:
 >>
 >> > And this is a problem, because article about D slices
 >> encourages to call
 >> > some raw memory (which almost never is directly manipulated
 >> and doesn't
 >> > appear in source code) as a dynamic array, and dynamic array
 >> as a slice.
 >>
 >> An array is simply consecutive elements in memory. There are two types
 >> of arrays: static (aka fixed-length) and dynamic.
 >
 > As a general programming notion - yes, in D (array spec page):
 > "Dynamic arrays consist of a length and a pointer to the array data."

Then the spec is wrong because that is the definition of a slice. The 
reason is, there is no dynamic array is sight below but a static array 
and a slice:

     int[10] arr;
     int[] slice = arr;
     assert(slice.ptr == &arr[0]);  // (yes, same as arr.ptr)

Even though 'slice' above "consists of a length a pointer to the array 
data" despite the language of the spec, that is not a dynamic array:

     slice[0] = 42;

The static array's element is changed, not some dynamic array's.

The correct description is that the 'slice' variable above is a slice, 
having the ability to refer to elements of a dynamic array and a static 
array.

(I know I am repeating the article at this point but it happens to be 
the fact.) If there is no dynamic array to speak of above, what is a 
dynamic array then? The answer is, dynamic array is an entity that is 
owned and managed by the D runtime.

For the above code to finally involve a dynamic array, we can add an 
element to 'slice':

     slice ~= 7;
     assert(slice.ptr != &arr[0]);

Now there is a dynamic array but it is not our 'slice' that is the 
dynamic array. Here is the proof:

     slice = arr[5 .. $];
     assert(slice.ptr == &arr[5]);

Has 'slice' been a dynamic array until that last assignment and suddenly 
become a slice again? No, D does not involve type changes like that. It 
has always been a slice, which is not the same thing as a dynamic array.

 > This actually kills two misinterpretations encouraged by array article
 > that a) dynamic array is some kind of runtime memory

I still think so.

 > b) that T[] data is not a dynamic array, it is a slice.

I still think so.

The spec must be outdated then; the array semantics have been finalized 
relatively recently (in 2009? or 2010?).

Ali



More information about the Digitalmars-d mailing list