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

Jonathan M Davis jmdavisProg at gmx.com
Wed Nov 7 01:29:00 PST 2012


On Wednesday, November 07, 2012 10:19:06 thedeemon wrote:
> On Wednesday, 7 November 2012 at 06:44:11 UTC, Jonathan M Davis
> 
> wrote:
> > On Wednesday, November 07, 2012 04:45:04 Malte Skarupke wrote:
> >> I don't anticipate that I will ever run into a situation where
> >> I want to append to a range without caring about whether it
> >> allocates and copies or not. If I want to append to a range, I
> >> will write the extra line to create a copy manually.
> >> Because of that I don't need the syntactic ambiguity of
> >> treating
> >> a range the same as an array.
> > 
> > In general, you can't append to ranges.
> 
> I assume Malte really meant slices, not ranges.

Well, there's no difference between a slice of an array and an array. There's 
no point in distinguishing them, and it's just going to cause confusion if you 
try and think of them as being any different from one another. Similarly, 
thinking of a dynamic array as a container is a bit mistaken, because dynamic 
arrays don't own or manage their own memory. The runtime does.

If you want an array that is never sliced, you have to make sure of that 
yourself (probably by wrapping it in class - even wrapping it in a struct 
wouldn't work, since it would be sliced when the struct was copied), and if 
you want to avoid reallocating when appending in the face of removing elements 
from the array, you'll have to manage that yourself as well. But if you're 
going that far to manage your own arrays, and you're wrapping them in another 
type, it might make the most sense to just not use arrays but rather allocate 
the memory yourself with malloc, and then have the wrapper manage its length. 
You lose concatenation and whatnot, but it's probably more efficient that way, 
and you avoid the problem of potentially screwing up and ending up with 
reallocations that you didn't expect. Dynamic arrays are meant to be 
sliceable, and trying to avoid letting them be sliced or otherwise letting the 
runtime manage them is likely more trouble than it's worth.

- Jonathan M Davis


More information about the Digitalmars-d mailing list