std.container.array - are these arrays passed by reference?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 30 18:51:57 PDT 2015


On Thursday, July 30, 2015 21:05:24 Harry P via Digitalmars-d-learn wrote:
> I'm trying to avoid the gc so I'm using std.container.array
> arrays instead of the standard ones. I know the standard arrays
> return by reference so I imagine that the nogc alternative is
> also passed by reference because it'd be a struct with a pointer
> and a length, yeah?
>
> I just want to check in case I'm wrong...

Well, aside from the fact that dynamic arrays don't quite have reference
semantics, std.container.array is not an array in that sense. It's like a
vector in C++ or an ArrayList in Java. It _is_ an actual reference type
though (unlike a dynamic array). Its payload is more complicated than a
simple pointer and length like a dynamic array, and it uses malloc and free
to manage its own memory.

But if all you want to do is avoid the GC with dynamic arrays, that works
just fine so long as you're not appending to them, reserving space to
append, or asking what its capacity is, since all of those involve the GC.
You can malloc memory and slice it to get a dynamic array. You just then
have to make sure that you manage the lifetime of that memory properly
(which generally means not treating the dynamic array as if it owned the
memory and being careful that no dynamic arrays which refer to the malloced
memory are still around when it's freed).

It's certainly easier to use std.container.array than using dynamic arrays
with malloc and free, but there's no reason that dynamic arrays would
require the GC except for operations related to appending, concatenation, or
using new (since new always uses the GC). Simply passing them around and
slicing them works just fine.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list