一个叫做GC的类,基本上它所做的就是增加和减少引用计数器
一个名为TObject的类,它扮演智能指针的角色(我重载了*和->操作符,还有=操作符) 下面是代码:GC.cpp
好吧,我试图实现一个垃圾收集器在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!为什么它的参考计数器也被更新了?
这是因为t和t2共享同一个gc实例。看看重载=操作符方法:-
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;
}