问题描述
我想从分配垃圾回收堆元素的数组,只有通过原始指针访问这些元素。能够回收的内存块后(而不是之前)所使用的所有指针的垃圾收集器指向它已超出范围?
我想这样做是这样的:
{
。为int * ptrToArray1 =(新INT [](100))PTR;
为int * ptrToArray2 = ptrToArray1;
为int * ptrToArray3 = ptrToArray1 + 10; ptrToArray1 + = 50;
ptrToArray2 + = 99; * ptrToArray1 = 123;
* ptrToArray2 = 456;
* ptrToArray3 = 789; ptrToArray1 - = 42;
ptrToArray2 - = 24; // ...等等...是数组数据保证是那里?
}
//现在所有的指针超出范围,能
//垃圾回收器回收该数组的内存块?
您的方案将正常工作。
两件事情:
- 垃圾收集器是保守的。这意味着它扫描栈,寄存器和GC堆的原始字。任何看起来像一个指针GC-分配的内存会被认为是这样的,因此保留了一块内存活。
- 垃圾收集器允许内部指针。这样做的原因是双重的。首先,它是相当普遍的(在系统语言)使用通过刚刚指针运算原始内存迭代,因此,GC必须处理这样的情况,其中只有一个偏移指针指向GC内存。其次,在D两种接口是真正从基本对象只是抵消了,所以这些都需要保持原来的对象现场。
这是值得注意的是,内部指针垃圾回收器的标记阶段显著放缓,但在如D一个系统的语言,不支持内部指针是不合理的。
最后,注意,如果你存储一个指向GC堆和栈/寄存器外GC-分配的内存的它不会被GC的的回升。也就是说,如果你存储一些阵列的 .ptr
在某些的malloc
'D内存,然后扔掉所有引用它,它不会被活考虑,例如
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:
- The garbage collector is conservative. That means it scans the raw words of the stack, registers, and the GC heap. Anything that looks like a pointer to GC-allocated memory will be considered to be such, and therefore keep that piece of memory live.
- The garbage collector allows interior pointers. The reason for this is two-fold. First, it's fairly common (in a systems language) to iterate through raw memory using just pointer arithmetic, so the GC has to handle a situation like that, where only an offset pointer points to the GC memory. Second, interfaces in D are really just offsets from the base object, so these need to keep the original object live.
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 .ptr
in some malloc
'd memory, and then throw away all references to it, it won't be considered live, for example.
这篇关于难道垃圾收集器preserve这是只由原始指针引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!