why does clearing an array set its capacity to 0?

Chris Cain via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 1 10:33:03 PDT 2014


In short:
> Why is this, and what do I do about it?

http://dlang.org/phobos/object.html#.assumeSafeAppend

On Tuesday, 1 July 2014 at 12:33:15 UTC, Vlad Levenfeld wrote:
> I'm trying to implement some wrappers atop preallocated arrays, 
> so I'm calling reserve in the constructor, have an invariant to 
> ensure that the array.ptr never moves, and use in-contracts to 
> make sure any insertion and appends don't put me over the array 
> capacity.
>
> I find that I'm able to safely add and remove elements (I 
> increment xor decrement the length when I do this) but when I 
> call clear on the backing array or set its length to 0, my 
> capacity also goes to 0.

As you noted in your followup post, decrementing also sets 
capacity to 0.

The reason is simple, observe:

auto arr = [1,2,3]

It is safe if you append 4 to that.

auto arr = [1,2,3,4]
auto other = arr[];
arr.length = 2;

It is *not* safe to append 5 to arr here, because doing so would 
change other to [1,2,5,4] which is (probably) not what you want 
(or, at least, you haven't made it explicit that you're okay with 
this behavior). Since slices are unaware of whether other views 
on memory exist, they must always reallocate if they've been 
shrunk to avoid the possibility of overwriting existing elements 
in other views of the array.

When you use "assumeSafeAppend", you are guaranteeing that either 
no other views exist, or if they do exist that you don't care if 
they are overwritten. Take note that the second case is *really 
bad* if your element type is immutable, for obvious reasons.


More information about the Digitalmars-d-learn mailing list