On Wednesday, 7 August 2013 at 15:21:56 UTC, Gary Willoughby wrote:
What's the D way of allocating memory? Do you guys just use malloc() and free()? Or are there functions in phobos that should be used? I just need a buffer of variable length allocating every now and then.

I usually use "new": It takes care of T.sieof, it initializes my memory to T.init, and conveniently returns a slice. Furthermore, the slice has "append" info, which is always a nice plus. This is really the equivalent of C++'s new.

If you want to do "semi-manual" memory management, you can use GC.malloc, which works like normal malloc, but is *still* managed by the GC. I'd actually recommend "GC.qalloc" over "GC.malloc": it's the same function, but qalloc actually returns more info, such as the total amount of memory *actually* allocated. This is very useful when you need a buffer of arbitrary size, as you get the most out of your allocation. The memory can also be eagerly marked as unused with "GC.free", although you'll still have to wait for a collect for it to actually be freed.

Finally, you have C's malloc and free. I don't have much to say about these that you shouldn't already know.

If you need a non-initialized buffer, but don't want to bother with a hand written [GC.]malloc, you can use phobos' std.array.uninitializedArray and std.array.minimallyInitializedArray. These conveniently return a slice of type T, containing N elements, but without actually initializing them. It's convenient.

Reply via email to