want to confirm: gc will not free a non-gc-allocated field of a gc-allocated object?
Steven Schveighoffer
schveiguy at gmail.com
Tue Jun 7 13:56:23 UTC 2022
On 6/6/22 6:18 PM, mw wrote:
> Hi,
>
> Suppose I have this code:
>
> ```
> class GCAllocated {
> float[] data;
>
> this() {
> // non-gc-allocated field
> this.data = cast(float[])(core.stdc.stdlib.malloc(nBytes)[0 ..
> nBytes]);
> }
> }
>
> void foo() {
> auto obj = new GCAllocated(); // gc-allocated owning object
> ...
> }
>
> ```
>
> So when `obj` is cleanup by the GC, obj.data won't be freed by the GC:
> because the `data` is non-gc-allocated (and it's allocated on the non-gc
> heap), the GC scanner will just skip that field during a collection
> scan. Is this understanding correct?
Others have given answers on this, but I just want to clarify -- the GC
does *not* use any type information to scan for pointers. The default GC
has one bit to tell it whether a block contains pointers or not (if
true, it will treat every word as if it were a pointer), and it does not
understand array references, just pointers. The precise GC has a bitmap
of which words in the block are pointers, and it also does not
understand array references.
So you are safe, it will see the pointer inside the array reference, and
see that it doesn't point at GC memory, so nothing further will be done.
-Steve
More information about the Digitalmars-d-learn
mailing list