Avoid deallocate empty arrays?
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Dec 17 18:42:54 UTC 2020
On Thu, Dec 17, 2020 at 06:10:25PM +0000, IGotD- via Digitalmars-d-learn wrote:
[...]
> b.m_buffer.length 2, b.m_buffer.capacity 31
> b.m_buffer.length 0, b.m_buffer.capacity 0
>
> capacity 0, suggests that the array has been deallocated.
Are you sure?
My understanding is that capacity is always set to 0 when you shrink an
array, in order to force reallocation when you append a new element.
The reason is this:
int[] data = [ 1, 2, 3, 4, 5 ];
int[] slice = data[0 .. 4];
writeln(slice.capacity); // 0
writeln(data.capacity); // 7 <--- N.B.
slice ~= 10;
writeln(slice); // [1, 2, 3, 4, 10]
writeln(data); // [1, 2, 3, 4, 5]
Notice that slice.capacity is 0, but data.capacity is *not* 0, even
after taking the slice. Meaning the array was *not* deallocated.
Why is slice.capacity set to 0? So that when you append 10 to it, it
does not overwrite the original array (cf. last line of code above), but
instead allocates a new array and appends to that. This is the default
behaviour because it's the least surprising -- you don't want people to
be able to modify elements of your array outside the slice you've handed
to them. If they want to append, they get a copy of the data instead.
In order to suppress this behaviour, use .assumeSafeAppend.
T
--
If you're not part of the solution, you're part of the precipitate.
More information about the Digitalmars-d-learn
mailing list