deleting items from 2d arrays

Sergey Gromov snake.scaly at gmail.com
Sat Aug 15 18:45:41 PDT 2009


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.


More information about the Digitalmars-d-learn mailing list