我想从垃圾收集堆中分配一个元素数组,并仅通过原始指针访问这些元素。垃圾收集器是否能够在所有指向它的指针超出范围之后(而不是之前)回收该内存块?
我正在考虑这样做:
{
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?
最佳答案
您的方案将起作用。
两件事情:
值得注意的是,内部指针显着减慢了垃圾收集器的标记阶段,但在像 D 这样的系统语言中,不支持内部指针是不合理的。
最后,请注意,如果您将指向 GC 分配的内存的指针存储在 GC 堆和堆栈/寄存器之外,则 GC 不会拾取它。也就是说,如果你存储一些数组的
.ptr
在一些 malloc
'd 内存,然后丢弃所有对它的引用,例如,它不会被认为是实时的。
关于arrays - 垃圾收集器是否保留仅由原始指针引用的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12192691/