Inability to dup/~ for const arrays of class objects

Steven Schveighoffer schveiguy at yahoo.com
Thu May 30 07:36:21 PDT 2013


On Thu, 30 May 2013 04:58:46 -0400, Maxim Fomin <maxim at maxim-fomin.ru>  
wrote:

> No, spec is right and article is wrong. It uses incorrect definition and  
> calls correct definitions as incorrect. Is exactly what is writing an  
> article calling dynamic array to be not a dynamic array but a banana and  
> latter calling original definition incorrect because according to the  
> article it is a banana.

The spec needs to be clarified.  I caution that the spec is misleading in  
the article:

"In fact, most D coders consider the D slice to be the dynamic array type  
-- it's even listed as a dynamic array type in the spec!"

A dynamic array is one that can add length, a slice is NOT a dynamic  
array, it is a view of a chunk of data.  Without the runtime managing  
dynamic arrays using the GC, the slice could not be extended.  When you  
"add length" to a slice, the runtime takes the following steps:

1. Is this slice pointing into a dynamic array?  If not, go to step 3
2. Can the dynamic array expand in place?  If so, do it
3. Create a new dynamic array that can hold the data plus the extra length  
(and perhaps some extra reserved space to amortize appending), copy the  
existing slice data to that new dynamic array, and update the slice to  
point at that array.

It does NOT deallocate the original data, nor does it change any other  
references to the original data, and this aspect is important.  The slice  
has no ownership of the data, it is a view.  We agree as coders not to  
care what happens to the old data or when the slice shifts views to a new  
dynamic array, in trade for the convenience and illusion of slices being  
similar to dynamic arrays.

Note also that when a slice "shrinks", it does nothing to alter the  
dynamic array size or data.

A slice is not a dynamic array, any more than a pair of iterators is a  
dynamic array.  It does behave similarly to a dynamic array through the  
magic of UFCS and the runtime.  But not exactly the same.

> static assert(typeof(slice) == typeof(int[])); // int[] type is dynamic  
> array

Your definition of dynamic array is wrong.  Built-in dynamic arrays in D  
have no formal type, the runtime manages them.

There is no sense in arguing further, if you think int[] is a dynamic  
array, you are simply using the wrong definition, and we must agree on  
these basics in order to have a meaningful discussion.

A good formal definition of a dynamic array can be found here:

http://en.wikipedia.org/wiki/Dynamic_array

It is what I read while writing that article, to make sure I got my  
definitions correct.  D's dynamic array is a "bounded size dynamic array."

-Steve


More information about the Digitalmars-d mailing list