deleting items from 2d arrays
Daniel Keep
daniel.keep.lists at gmail.com
Sat Aug 15 21:15:17 PDT 2009
Sergey Gromov wrote:
> Fri, 14 Aug 2009 13:55:18 +1000, Daniel Keep wrote:
>
>> void dropElement(T)(ref T[] arr, size_t i)
>> {
>> assert( i < arr.length );
>> arr[i] = arr[$-1];
>> arr = arr[0..$-1];
>> }
>
> I think it's important to erase the last element after the move to make
> sure no dangling references to unused data are left in a memory area you
> don't manage anymore:
>
> | void dropElement(T)(ref T[] arr, size_t i)
> | {
> | assert( i < arr.length );
> | arr[i] = arr[$-1];
> arr[$-1] = T.init;
> | arr = arr[0..$-1];
> | }
>
> This is a sad consequence of conservative garbage collection.
Excellent point; I forgot about that.
More information about the Digitalmars-d-learn
mailing list