Inability to dup/~ for const arrays of class objects

Ali Çehreli acehreli at yahoo.com
Wed May 29 23:21:37 PDT 2013


On 05/29/2013 06:54 PM, Peter Williams wrote:

 > On 30/05/13 10:49, Peter Williams wrote:
 >> On 30/05/13 09:45, Ali Çehreli wrote:

 >>>    http://dlang.org/d-array-article.html

 > Thinking about this some more, it seems I still need the const even with
 > pass by value to reassure the caller that his array won't be altered. So
 > the problem doesn't go away it just changes slightly.

It is sensible that the parameter be const-element, non-const-slice:

     void foo(const(int)[] arr);

 > I find the mechanism described in the article a little disconcerting and
 > it certainly needs more publicity as it's a bug in waiting for the
 > unwary.

It certainly is disconcerting. Performance have played a big role in the 
current semantics of slices.

 > Wouldn't a better rule for pass by value be that any changes to
 > the data part of the array (including assignment to an element) causes
 > reallocation of the entire data portion.

The type of a slice parameter is not different than a local slice 
variable. Since we wouldn't want an entire copy of the elements due to 
an element mutation:

     int[] whole = // ...;
     int[] firstHalf = whole[0 .. $/2];
     firstHalf = 42;    // this should affect whole

Moving the last two lines to a new function should not change meaning:

     int[] whole = // ...;
     setFirstHalf(whole, 42);  // should still affect whole

Ali



More information about the Digitalmars-d mailing list