Create uninitialized dynamic array

Adam D. Ruppe destructionator at gmail.com
Thu Oct 5 21:03:34 UTC 2017


On Thursday, 5 October 2017 at 20:52:00 UTC, Igor Shirkalin wrote:
> Doesn't it mean we have to avoid GC for such large blocks? And 
> what if we need a lot blocks with less sizes?

No, it can work, especially if you are on 64 bit. Just if it is 
trivial I'd malloc it, but if the lifetime is nontrivial, sure, 
GC it.

The GC.malloc function from `import core.memory;` works just like 
malloc, except the garbage collector is aware of it and will 
collect eventually:

http://dpldocs.info/experimental-docs/core.memory.GC.malloc.html


int[] data = (cast(int*) GC.malloc(SOMETHING * int.sizeof, 0, 
typeid(int)))[0 .. SOMETHING];


Note that `typeid` returns the TypeInfo for that type, so you can 
pass it there.

Then the GC will collect if you like.

> Usually the block(s) is scoped with some more complex way, so 
> it is good to pass it to GC for management.

Yeah, that's good too.


More information about the Digitalmars-d-learn mailing list