Setting array length to 0 discards reserved allocation?

Andrew Godfrey via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 19 16:58:57 PDT 2014


On Sunday, 17 August 2014 at 07:33:01 UTC, ketmar via 
Digitalmars-d wrote:
> On Thu, 14 Aug 2014 06:46:40 +0000
> Andrew Godfrey via Digitalmars-d <digitalmars-d at puremagic.com> 
> wrote:
>
> sorry for the late answer.
>
>> Don't think I'm being flippant, but I have trouble 
>> interpreting such feedback, because D's dynamic array 
>> semantics ARE complicated.
> and it will be even more complicated if we will rename 'em to 
> 'array
> references'.
>
> i completely agree that D dynarray docs can be made clearer and 
> i
> appreciate any efforts which makes docs better. i'm just against
> 'reference' term -- seems that i'm from that minority that 
> becomes
> immediately confused when reading 'array reference'. what i 
> expect from
> 'reference' is that this code works:
>
>   void foo (int[] a) {
>     a ~= 42;
>   }
>   ...
>   int[] arr;
>   arr ~= 666;
>   foo(arr);
>   assert(arr.length == 2 && arr[1] == 42);
>
> but it doesn't. so arrays clearly aren't 'references' (as 
> 'reference',
> to my opinion, should keep 'pass by reference' semantics in 
> this case).
>
> so maybe we should coin some new word to describe dynarrays in 
> D.

Maybe. But consider that if "a" was a class and "~=" was instead
"=", you would have the same confusion. As in:
  void foo(MyClass a) {
     a = new MyClass;
  }

In either case, we are "passing a reference by value".
So operations on the referent affect the passed object/array, but 
operations
on the reference do not.

The further surprise is caused because concatenation affects the 
_reference_.
In fact it doesn't affect the referent at all!
Good example. Consider that this works:

void foo (int[] a) {
   a[0] = 42;
}

int[] arr;
arr ~= 666;
foo(arr);
assert(arr.length == 1 && arr[0] == 42);


More information about the Digitalmars-d mailing list