Arrays passed by almost reference?

Ali Cehreli acehreli at yahoo.com
Sun Nov 8 09:43:49 PST 2009


Andrei Alexandrescu Wrote:

> Ali Cehreli wrote:

> > I don't think that this is easy to explain to a learner; and I think that is a good indicator that there is a problem with these semantics.
> 
> The ball is in your court to define better semantics.
> 
> Andrei

I thought I passed the ball back to you in this thread:

  http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=100318

It didn't attract any interest... :)

Here are some points as teasers:

1) The term "dynamic array" and its distinction from "slice" is detrimental to understanding D's arrays, and is against their nature.

For example, is 's2' valid below?

void main()
{
    int[] a = new int[11];
    int[] s = a[2..8];

    a = new int[55];

    int[] s2 = s[2..6];
}

If so, has 's' been "promoted" to a dynamic array? What happens is, even 'a' was a slice to begin with. It was providing access to the 11 consecutive objects that is being owned by the garbage collector.

My point is, even the left hand of the first initialization is a slice:

    int[] slice = new int[11];

The expression 'new int[11]' creates 11 elements as a side effect, and returns "a slice to all of those elements."


2) The best that I can describe the semantics of slices is "discretionary share." It is like sharing a number of resources by a number of entities. Like, two companies sharing a cubicle space, where both are free to change the contents of cubicles.

They can both add a new cubicle that is not shared by the other (s~=1). They can both leave the "sharing" of cubicles at any time an soon as they see unfit.

This is a totally at-will arrangement between the two parties.

3) By accepting the above view, the exception of "slices are passed by reference" disappears too: Slices are passed by value as well. What happens is, the slice parameters starts "sharing" (or provides access to) all of the elements that the original slice is sharing.

Same with assignment: It creates a sharing contract.

I appreciate any comments.

Ali




More information about the Digitalmars-d mailing list