Arrays are sufficient for ArrayLists? Really??

Steven Schveighoffer schveiguy at yahoo.com
Mon May 16 12:41:17 PDT 2011


On Mon, 16 May 2011 15:23:31 -0400, Mehrdad <wfunction at hotmail.com> wrote:

> Steven:
>> You need to do arr.assumeSafeAppend();  Otherwise, the runtime is no
> aware of your invalidation of the last element.
>
> See my edit on SO: http://stackoverflow.com/q/6015008/541686

I'm not an SO user, so I'll post my answer here:

assumeSafeAppend is named that way because you are making an assumption,  
possibly an unsafe one :)  You are saying, "hey, runtime, assume that  
despite what you know about this array's data, it's safe to append in this  
case," and the runtime says "ok, boss, no problem."  It cannot tell that  
you intended to use that data you have just invalidated.

What you want to do is determine if the array is safe to append *before*  
you eliminate the elements at the end (i.e. the elements you are "throwing  
away" are at the end of valid data anyways).  You can do this with the  
capacity property:

auto oldcap = arr.capacity;

// do your dirty work
...

if(oldcap) // capacity != 0 means you could originally append to this  
array, or that it filled up the block.
    arr.assumeSafeAppend();

This should do the trick.

-Steve


More information about the Digitalmars-d mailing list