好的,我正在尝试使用引用计数的概念在C ++(一个非常基本的)中实现垃圾收集器,它可以工作,但有些东西我不明白。
我有两个班:
#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!为什么它的参考计数器也被更新了?
答案 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;
}