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

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 5 19:19:33 PST 2012


On Tuesday, November 06, 2012 03:28:09 Malte Skarupke wrote:
> Thanks, that explains it well. I must admit that I didn't fully
> understand slices before. I've read the linked article and am
> baffled that this is seen as acceptable behavior. I will most
> certainly never use dynamic arrays or slices again for anything
> that needs to grow or shrink dynamically.

It has to work this way, or it would totally screw up slices. You can't append 
to a slice which is not the last slice in the block without affecting the 
slices after it, so a reallocation must occur. And it would create too much 
overhead for the runtime to try to figure out whether it's safe for a slice to 
be considered the last slice in the block when you decrement its length. So, 
if you want it to be considered the last one, you have to keep track of it and 
tell the runtime yourself.

This sort of thing wouldn't be a problem if you couldn't slice arrays, but not 
being able to do that would be a huge loss. So, you either need to manage it 
yourself or create a type which will do that for you (e.g. std.container.Array 
should do that, though unfortunately, it looks like it doesn't currently call 
assumeSafeAppend like it should).

- Jonathan M Davis


More information about the Digitalmars-d mailing list