DIP 1025--Dynamic Arrays Only Shrink, Never Grow--Community Review Round 1

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Nov 11 19:18:53 UTC 2019

On Monday, November 11, 2019 11:54:04 AM MST Ola Fosheim Grøstad via 
Digitalmars-d wrote:
> On Monday, 11 November 2019 at 17:28:09 UTC, Jonathan M Davis
> wrote:
> > How on earth do D dynamic arrays change their type? int[] is
> > always int[].
> Well, what we mean by "type" can of course be debated, but anyway:
> Case 1:
>      char[] a = new char[2];
>      writeln(a.ptr);
>      if (false) a.length = 1;
>      a.length = 2;
>      writeln(a.ptr);  // same pointer
> Case 2:
>      char[] a = new char[2];
>      writeln(a.ptr);
>      if (true) a.length = 1;
>      a.length = 2;
>      writeln(a.ptr); // different pointer
> So, whether it extends inline depends what you did with the
> object dynamically. It isn't determined statically. Even though
> in this case that would be possible.
> Kinda like the difference between an open and closed file,
> whether it is open or not depends on some dynamic external cause
> (if it exists on the files system).

So what if the pointer's value changed? Objects have their members mutated
all the time. That doesn't make them different types. If you want to know
whether appending to a dynamic array will result in a new buffer being
allocated (with the elements being copied over, and the ptr member of the
dynamic array being mutated), then check whether the capacity is large
enough to contain the elements being appended. If it is, then the GC can
expand the dynamic array in-place. If it isn't, then the GC has to allocate
a new buffer, copy the elements over, and mutate the dynamic array's ptr and
length members to point to the new buffer. And that's the same regardless of
what kind of memory backs the dynamic array (it's just that there's never
enough capacity to grow in-place if the underlying buffer wasn't allocated
by the GC for dynamic arrays). I don't understand why you'd think that a
dynamic array being in a different state based on what you did with it would
in any way make it a different type. It's perfectly normal for the behavior
of an object to change based on its state.

- Jonathan M Davis

More information about the Digitalmars-d mailing list