I’d like to allocate an array of elements from the garbage collected heap, and access those elements only through raw pointers. Is the garbage collector capable of reclaiming that block of memory after (and not before) all the pointers that used to point to it have gone out of scope?
I was thinking of doing it like this:
{
int* ptrToArray1 = (new int[](100)).ptr;
int* ptrToArray2 = ptrToArray1;
int* ptrToArray3 = ptrToArray1 + 10;
ptrToArray1 += 50;
ptrToArray2 += 99;
*ptrToArray1 = 123;
*ptrToArray2 = 456;
*ptrToArray3 = 789;
ptrToArray1 -= 42;
ptrToArray2 -= 24;
//... and so on ... Is the array data guaranteed to be there?
}
// Now that all the pointers are out of scope, can the
// garbage collector reclaim the memory block of that array?
Your scenario will work.
Two things:
It’s worth noting that interior pointers significantly slow down the marking phase of the garbage collector, but in a systems language like D, not supporting interior pointers would be unreasonable.
Finally, note that if you store a pointer to GC-allocated memory outside the GC heap and the stack/registers, it will not be picked up by the GC. That is, if you store some array’s
.ptrin somemalloc‘d memory, and then throw away all references to it, it won’t be considered live, for example.