Passing dynamic arrays

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 29 06:13:17 PST 2010


On Fri, 26 Nov 2010 14:50:27 -0500, Bruno Medeiros  
<brunodomedeiros+spam at com.gmail> wrote:

> On 09/11/2010 12:42, Steven Schveighoffer wrote:
>> On Mon, 08 Nov 2010 21:29:42 -0500, Jesse Phillips
>> <jessekphillips+D at gmail.com> wrote:
>>
>>> 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.
>>
>> It depends on your definition of reference type. I agree with Daniel. If
>> you want to get into academic definitions, yes, 'technically' an array
>> is a reference, but it's confusing to someone who's not interested in
>> exploring the theoretical parts of computer science.
>>
>
> What do you mean "depends on your definition of reference type" ? I  
> think that what a reference type is, is generally understood fairly well  
> by the majority of developers, even if understood implicitly. I think  
> our confusion here has more to do to what we consider an "array", rather  
> than what we consider to "reference type to be. See below.

A class is a reference type.  Every operation on a class instance operates  
on all aliases to that class, only assignment to another class instance of  
the same type decouples it.

Consider these two statements:

"a class is a reference type"

class C
{
    int length;
}

foo(C c)
{
   c.length = 5; // because a class is a reference type, this affects the  
original, right?
}

"an array is a reference type"

foo(int[] arr)
{
    arr.length = 5; // because an array is a reference type, this affects  
the original, right?  No?!!!
}

This is the major confusion that I think people see.  I would say people  
assume a "reference type" means that the reference's members are all  
shared between all aliases.  For an array, it is one level removed, and  
that confuses the hell out of people.  But the power gained by doing D's  
way is worth way waaaay more than confusing some noobs.

Note that many people are used to object-based languages such as C# and  
Java where arrays actually *are* class instances, and therefore full  
reference types.

-Steve


More information about the Digitalmars-d mailing list