Create uninitialized dynamic array

Igor Shirkalin mathsoft at inbox.ru
Thu Oct 5 20:52:00 UTC 2017


On Thursday, 5 October 2017 at 20:19:15 UTC, Adam D. Ruppe wrote:
> On Thursday, 5 October 2017 at 19:59:48 UTC, Igor Shirkalin 
> wrote:
>> I want to quickly fill it with my own data and I do not want 
>> to waste CPU time to fill it with zeros (or some other value).
>
> You could always just allocate it yourself. Something that 
> large is liable to be accidentally pinned by the GC anyway, so 
> I suggest:
>
> int[] data;
> int* dataptr = cast(int*) malloc(SOMETHING * int.sizeof);
> if(dataptr is null) throw new Exception("malloc failed");
> scope(exit) free(dataptr);
> data = dataptr[0 .. SOMETHING];
> // work with data normally here
>
>
> Just keep in mind it is freed at scope exit there, so don't 
> escape slices into it.

Thank you, Adam, for pinpoint answer.

Doesn't it mean we have to avoid GC for such large blocks? And 
what if we need a lot blocks with less sizes? I'm from C++ world 
but... I like GC.
Usually the block(s) is scoped with some more complex way, so it 
is good to pass it to GC for management.
Maybe (say LDC) compiler can reject this unuseful initialization 
on simplest cases.

Shortly, I'm still in doubt.




More information about the Digitalmars-d-learn mailing list