Arrays passed by almost reference?

Travis Boucher boucher.travis at gmail.com
Thu Nov 5 13:35:35 PST 2009


>> I am not fully against pass-by-ref arrays, I just think in passing by
>> reference all of the time could have some performance implications.
> 
> OK, make 2 different types then: slices (value types, can't append, they
> are only a view on other's data) and dynamic arrays (reference type, can
> append, but a little slower to manipulate).
> 
> It's a shame this idea didn't came true after all...
> 

I just wonder if that would be confusing.

Static arrays of 2 different sizes are 2 different types.

Another example of how it is already confusing:

--
int[2] a = [1, 2];
int[] b = [11, 22, 33];

b = a;
a[0] = 111;

/*
  Now both a and b == [111, 2], instead of the intuitive b == [1,2], c 
== [111, 2].  They point at the same data.
*/
b.length = b.length + 1; // now at different data.

a[1] = 222;
/* a == [111, 222], b == [111,2,0] as expected */
--

Something that is nice about dynamic arrays is how they can intermix 
with static arrays (int[] b = int[2]) in an efficient (and lazy copying) 
manor.  It makes functions like this fast and efficient:

int addThemAll(int[] data) {
     int rv = 0;
     foreach (i,v; data) rv += v;
     return rv;
}

Since an implicit case from a static array to a dynamic array is cheap, 
and slicing an array to a dynamic array is cheap (as long as you are 
only reading from the array).

I don't see how separating them to have different call semantics solves 
the problem.  However making a clearer definition of each (in 
documentation for example) might be helpful.

Me, being new D, I am glad this thread exists because I can see how I 
could have shot myself in the foot in the future without playing around 
and learning the difference.



More information about the Digitalmars-d mailing list