好的,我正在尝试使用引用计数的概念在C++(非常基本的一个)中实现垃圾收集器,它可以工作,但是有些事情我不理解。
我有两节课:
一个名为TObject的类,它充当智能指针的角色(我重载了*和->运算符,以及=运算符)
气相色谱仪
#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;
}
};
这是我主要测试的方式:
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;
}
关于c++ - C++-使用引用计数的基本垃圾收集器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40443081/