Slices and array appending

Jonathan M Davis jmdavisProg at gmx.com
Sun Oct 21 21:59:16 PDT 2012


On Monday, October 22, 2012 01:35:29 cal wrote:
> Just want to make sure I understand this properly:
> 
> I have a large dynamic array (whose elements are immutable) which
> only ever grows. I also have a whole lot of small slices into
> this array, the slices never change, and they don't span the
> entire contents of the array (they are just pieces).
> 
> Now if I append to the large array, and the runtime needs to
> re-allocate to accommodate the change in size, none of the pieces
> of the original array which are referred to by the slices can be
> freed, right? So I end up basically with two copies of the
> original large array, however the first version will now have
> little pieces missing from it (wherever the slices don't refer).
> 
> Is that correct?

Blocks of memory are allocated and freed as a whole. When an array is forced 
to be reallocated, then a new block of memory is allocated for it, and any 
existing slices continue to refer to the original block of memory. The 
original block will not be freed until there are no more slices which refer to 
it. You really should read this article if you want to know how arrays work in 
D:

http://dlang.org/d-array-article.html

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list