On Tuesday, 16 March 2021 at 23:49:00 UTC, H. S. Teoh wrote:
[snip]
Note that T[] is just a slice, not the dynamic array itself.
The dynamic array is allocated and managed by the GC when you
append stuff to it, or when you create a new array with `new`
or an array literal.
None of the latter, however, precludes you from using T[] for
memory that you manage yourself. For example, you could do this:
double[] data;
data = cast(double[]) malloc(n * double.sizeof)[0 .. n];
Now you have a slice to memory you allocated yourself, and you
have to manage its lifetime manually. When you're done with it:
free(data.ptr);
data = []; // null out dangling pointer, just in case
The GC does not get involved unless you actually allocate from
it. As long as .ptr does not point to GC-managed memory, the GC
will not care about it. (Be aware, though, that the ~ and ~=
operators may allocate from the GC, so you will have to refrain
from using them. @nogc may help in this regard.)
T
This is one of those things that is not explained well enough.