C ++ - 使用引用计数的基本垃圾收集器

时间:2016-11-05 20:51:48

标签: c++ garbage-collection smart-pointers reference-counting

好的,我正在尝试使用引用计数的概念在C ++(一个非常基本的)中实现垃圾收集器,它可以工作,但有些东西我不明白。
我有两个班:

  • 一个名为GC的类,基本上它只是递增和递减引用计数器
  • 一个名为TObject的类,它扮演智能指针的角色(我重载了*和 - >运算符,还有=运算符)
  • 以下是代码: GC.cpp

    #include <iostream>
    
    using namespace std;
    
    class GC {
    public:
        GC(){
            this->refCount = 0;//Initialisation du compteur à zero
        }
    
        void incrementRef(){
            this->refCount++;//Incrémentation du compteur de references
        }
    
        int decrementRef(){
            return this->refCount--;//Décrementation du compteur de references
        }
    
        int getCounter(){//Getter du compteur de references
            return refCount;
        }
        ~GC(){}
    
    private:
        int refCount; //Compteur de references
    };
    

    TObject.cpp:

    #include <iostream>
    #include "GC.cpp"
    
    using namespace std;
    
    template <class T>
    class TObject {
    
    T *p;
    GC *gc;
    
    public:
        TObject(T *p){
            cout<<"refobject"<<endl;
            this->p = p;
            gc = new GC();
            this->gc->incrementRef();
        }
    
        virtual ~TObject(){//Destructeur
            cout<<"delete TObject"<<endl;
            if(this->gc->decrementRef() == 0){
                delete p;
                delete gc;
            }
        }
    
        T* operator->(){//Surcharge de l'opérateur d'indirection
            return p;
        }
    
        T& operator*() const {//Surchage de l'opérateur
            return *p;
        }
    
        TObject<T>& operator=(const TObject<T> &t){
            if(this->gc->decrementRef() == 0){
                delete p;
                delete gc;
            }
            this->p = t.p;
            this->gc = t.gc;
            this->gc->incrementRef();
            return *this;
        }
    
        GC getGC(){
            return *gc;
        }
    };
    

    这是我在main中测试的方式:

    TObject<int> t(new int(2));
    cout<<"t1 counter: "<<t.getGC().getCounter()<<endl;//Displays 1
    TObject<int> t2(NULL);
    cout<<"t2 counter: "<<t2.getGC().getCounter()<<endl;//Displays 1
    t2 = t;
    cout<<"t1 counter: "<<t.getGC().getCounter()<<endl;//Displays 2, why?
    cout<<"t2 counter: "<<t2.getGC().getCounter()<<endl;//Displays 2
    

    我没有得到它,我在t2中复制了t并且我没有更新t1!为什么它的参考计数器也被更新了?

    1 个答案:

    答案 0 :(得分:2)

    这是因为,t和t2共享相同的gc实例。查看你的overloaded =运算符方法: -

    TObject<T>& operator=(const TObject<T> &t)
    {
       if(this->gc->decrementRef() == 0)
       {
            delete p;
            delete gc;
       }
       this->p = t.p;
       this->gc = t.gc;  // you are using same gc. Instead, you must be using
                         //  this->gc = new GC(); 
       this->gc->incrementRef();
       return *this;
    }