C ++ - 优化我的GC

时间:2012-10-01 17:51:54

标签: c++ garbage-collection

这是我的垃圾收集器代码:(它发现该对象不再可用的地方)

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方法刚刚出现在我的大脑中,并且没有错误。

1 个答案:

答案 0 :(得分:2)

如果你的应用程序需要垃圾收集,我实际上建议使用已经原生支持它的许多语言之一,而不是试图将这样的功能添加到C ++。

如果你需要的是C ++中一个理智的内存管理模型,你应该通过智能指针来使用RAII。对于内存管理,这意味着使用适当的智能指针来处理所有内存分配需求。您可以通过C ++ 11获取这些指针,或者如果您无法通过boost获得这些指示。