Static Constructors
Gide Nwawudu
gide at btinternet.com
Sun Oct 5 10:26:58 PDT 2008
On Sat, 4 Oct 2008 14:02:43 -0400, "Steven Schveighoffer"
<schveiguy at yahoo.com> wrote:
>
>"Saaa" <empty at needmail.com> wrote in message
>news:gc8314$24e0$1 at digitalmars.com...
>>
>>>
>>> First one allocates new memory block.
>>> Second one attempts to erase an element in-place. Dupping, however,
>>> allocates new memory, too.
>>> The best solution would be as follows:
>>>
>>> void eraseNth(ref T[] data, int n) {
>>> data[n] = data[$-1];
>>> data.length = data.length - 1;
>>> }
>>
>> Yay, thats how I do it :)
>
>If you want the memory removed as soon as possible, you should zero out the
>last element, otherwise, the GC will still think the element is being
>pointed to:
>
>data[n] = data[$-1];
>data[$-1] = null;
>data.length = data.length - 1;
>
>-Steve
>
The following code outputs [0 4 2 3], is this a bug in D2?
int n = 1;
int[] data = [0,1,2,3,4].dup;
writeln(data); // [0 1 2 3 4]
data[n] = data[$-1];
data[$-1] = 0;
data.length = data.length - 1;
writeln(data); // [0 4 2 3]
Gide
More information about the Digitalmars-d-learn
mailing list