Passing dynamic arrays
Jesse Phillips
jessekphillips+D at gmail.com
Mon Nov 8 18:29:42 PST 2010
Daniel Gibson Wrote:
> On Tue, Nov 9, 2010 at 1:24 AM, Jesse Phillips
> <jessekphillips+D at gmail.com> wrote:
> >
> > The array-struct is the reference, so it is what gets compared. That means both the internal pointer and length must be the same. Just because the reference is more than an address does not make it any less a reference.
> >
>
> Unlike in C, a D array is more than a reference.
> An array is the data (or a reference to its data) + metadata (its
> length) - the metadata belongs to the array (and not to the
> reference).
If you are using the definition of reference which would include C pointers (i.e. not C++ references), then there is nothing in the definition of reference that precludes it from having meta data.
"In distributed computing, the reference may contain more than an address or identifier; it may also include an embedded specification of the network protocols used to locate and access the referenced object, the way information is encoded or serialized."
http://en.wikipedia.org/wiki/Reference_(computer_science)
> This means that, when you say "the array is passed by reference" one
> expects that also the arrays length is passed by reference - because
> the length belongs to the array.
This is a good point. Though if the length did stay with the array, it is still reasonable that a reallocation of the array would cause the reference to no longer point to the same array.
> > The distinction is that an Array can have its reference changed by resizing (which is not an option for other reference types).
> >
>
> If that is not an option for any other reference type, why should it
> be an option for arrays? That is just inconsistent and doesn't make
> any sense.
Well, if you can come up with a good definition for what "increasing the size of a class" would do, then maybe it should be added.
It really doesn't matter. Arrays are their own type, the have their own semantics. It does help to think of them in terms of slices (which is what TDPL refers to them as), yet that does not remove the fact that they are in dead a reference type.
Many times familiar terms are used so that a behavior is quickly understood. For example it is common to say that arrays in C is just a pointer into a memory location. But in reality that is not true.
http://www.lysator.liu.se/c/c-faq/c-2.html
>
> No, Arrays should not be considered reference types when passed to a function.
> As someone else said before: Logically you don't pass the array but a
> slice that contains the whole array.
>
> Cheers,
> - Daniel
More information about the Digitalmars-d
mailing list