这是我的垃圾收集器代码:(它发现该对象不再可达)
HEADER* ptr;
static int gc_checked_count;
static void** gc_checked_array;//=malloc(10000);
//This method called when the the pointer in this class is changing.
inline void Destruct() {
//If the pointer is null or it is alright pointed from the stack then
if ((!ptr?true:ptr->getOnStack()))
//exit.
return;
//GC_THROW_USED uses this variable. - need to zero it.
gc_checked_count=0;
try {
GC_THROW_USED(ptr);
//If this function didn't threw a bool ,then run it's finalize method
//getType is temporary as function pointer.
((void(*)(void*))ptr->getType())(ptr);
//, free his information
free(ptr->getArray());
//, free itself
free(ptr);
//and zero `ptr` because it isn't valid anymore.
ptr=0;
}
catch (bool x) {
//If reachable then don't do anything to this object.
//Keep yourself alive because life is good :).
}
}
inline void GC_THROW_USED(HEADER* p) {
//Check if this pointer didn't checked by this method
for (uint i=0;i<gc_checked_count;++i)
//, if yes then
if (gc_checked_array[i]==p)
//exit.
return;
//Append this pointer to the checked list
gc_checked_array[gc_checked_count++]=p;
//If this pointer is pointed on the stack then
if (p->getOnStack())
//throw. (it says that `ptr` is reachable.)
throw false;
uint count=p->getCount();
HEADER** pArray=(HEADER**)p->getArray();
for (uint i=0;i<count;++i)
//Run this method on it's containers too. (Until exception or there is no object to run on)
GC_THROW_USED(pArray[i]);
}
在任何声明之前,都有一个解释它的注释。就像你看到的,这个 GC 在指针的容器上运行(谁“知道”这个指针),直到它发现一个容器在堆栈上,然后这意味着这个对象是可访问的。如果没有,则最终确定此对象并释放它。
真正的问题:有没有办法优化这个过程来提高性能?//Run this method on it's containers too. (Until exception or there is no object to run on)
部分(在代码的最后几行)我可以剪切它并且它会运行而没有错误?
我有点困惑,因为这个 GC 方法刚刚出现在我的脑海中,并且没有错误。