On Monday, 28 July 2014 at 22:29:04 UTC, Ali Çehreli wrote:
On 07/27/2014 01:49 AM, Jonathan M Davis wrote:
> difference between a dynamic array and a slice (there really
isn't any).
At the risk of beating this never-dying horse, when you say
that, I don't think you can explain the following code:
int[] a = [ 1, 2, 3 ];
int[] b = a;
According to your terminology, 'a' is a dynamic array and 'b'
is another dynamic array. Knowing how good you know D, I can't
understand how you think that way. In fact, both 'a' and 'b'
are slices into the single dynamic array. The dynamic array is
managed by the GC. So, there are three entities in that code:
One dynamic array and two slices.
It's simple, D's dynamic arrays _never_ own their memory. It's
owned by the GC, or it's a slice of a static array, or it points
to a buffer that was malloc-ed, etc. The type T[] says _nothing_
about who or what owns the memory or what backs the array.
Understanding how it works when they're generated by the GC is
very helpful in determining when a dynamic array / slice is
likely to be reallocated, but it's pretty irrelevant to the type
itself.
In your example, both a and b are dynamic arrays which are slices
of the same underlying block of memory. It's a and b which are
the dynamic arrays, not the buffer. From the type system's
perspective, this would be the same
int[3] z = [1, 2, 3];
int[] a = z;
int[] b = a;
a and by are still exactly the same type - dynamic arrays - and
they will behave exactly the same save for the fact that due to
the fact that they're now backed by a static array rather than
the GC, their capacity is guaranteed to be 0, and it's unsafe for
them to escape from the scope of z.
The underlying buffer for a GC-backed dynamic array isn't even a
D array. It's a druntime-specific data structure which holds a
buffer via pointer.
The array article does a great job of explaining a lot of the
details about how D arrays work (especially those backed by the
GC), but it got the terminology wrong, and I definitely think
that it should be fixed.
- Jonathan M Davis