C++ - Basic garbage collector using reference counting -
ok, i'm trying implement garbage collector in c++ (a basic one) using concept of reference counting, , works there don't understand.
have 2 classes:
#include <iostream> using namespace std; class gc { public: gc(){ this->refcount = 0;//initialisation du compteur à 0 } 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; } };
and here how tested in 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
i don't it, copied t in t2 , did not update t1! why reference counter updated too?
it's because, both t , t2 sharing same gc instance. @ overloaded = operator method :-
tobject<t>& operator=(const tobject<t> &t) { if(this->gc->decrementref() == 0) { delete p; delete gc; } this->p = t.p; this->gc = t.gc; // using same gc. instead, must using // this->gc = new gc(); this->gc->incrementref(); return *this; }
Comments
Post a Comment