How do you remove/insert elements in a dynamic array without allocating?

monarch_dodra monarchdodra at gmail.com
Wed Nov 7 02:44:15 PST 2012


On Wednesday, 7 November 2012 at 10:18:51 UTC, Jonathan M Davis 
wrote:
> And I find the whole length vs capacity bit in Array
> highly confusing, because it looks like the length of the 
> payload is used for
> length, when I would have expected the length of the payload to 
> be the
> capacity and for there to be a separate length for the actual 
> number of
> elements.

I was confused the first time too, but the payload's "slice" in 
only as big as the elements it is holding, and it "knows" there 
is more room after the slice, up to _capacity.

This keeps things relatively simpler for most of Array's 
implementation, and keeps all the complexity inside the Payload 
structure.

So yeah, their semantic is what you'd expect actually.

On Wednesday, 7 November 2012 at 10:18:51 UTC, Jonathan M Davis 
wrote:
> By the way, monarch_dodra, since you've been messing around 
> with Array
> recently, I would point out that it looks like setting the 
> length doesn't work
> properly if you set it greater than the current length, let 
> alone greater than
> the current capacity.  _capacity is not adjusted if newLength 
> is greater than
> it, and no calls to GC.removeRange or GC.addRange are made, so 
> it doesn't look
> like newly allocated memory is being tracked by the GC like it 
> should if
> length is allocating it.

I kind of wanted to stay out of that part of the code, but good 
catch. This creates an assertion error:
--------
     auto a = Array!int();
     a.length = 5;
     a.insertBack(1);
--------
Because at the point of insert back, length > capacity...

I'll correct the issues anyways. Good point about the 
GC.removeRange a,d GC.addRange too.


More information about the Digitalmars-d mailing list