学习实践垃圾回收的一个小代码
采用引用计数
每次多一个指针指向这个分配内存的地址时候 则引用计数加1
当计数为0 则释放内存 他的难点在于指针之间的复制 所有权交换 计数的变化
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
class GCInfo {
unsigned int refcount_;
T* ptr_;
public:
GCInfo(T* ptr) {
refcount_ = 1;
ptr_ = ptr;
}
void IncreRef() {
refcount_++;
}
void DecreRef() {
refcount_--;
}
unsigned int GetRef() const{
return refcount_;
}
T* GetPoint() const{
return ptr_;
}
};
template<typename T,int size = 0>
class GCPtr {
//static vector<GCInfo<T>> gclist;
GCInfo<T>* pgcInfo_;
public:
GCPtr(T* t){
cout << "creatr ptr: " << typeid(T).name()
<< " addr: " << t << endl;
pgcInfo_ = new GCInfo<T>(t);
}
GCPtr(const GCPtr& gcp) {
pgcInfo_ = gcp.pgcInfo_;
pgcInfo_->IncreRef();
}
GCPtr& operator=(const GCPtr& gcp) {
pgcInfo_ = gcp.pgcInfo_;
pgcInfo_->IncreRef();
}
T* GetPtr() {
return pgcInfo_->GetPoint();
}
~GCPtr() {
pgcInfo_->DecreRef();
if (pgcInfo_->GetRef() == 0) {
cout << "delete ptr: " << typeid(T).name()
<< " addr: " << pgcInfo_->GetPoint() << endl;
delete pgcInfo_->GetPoint();
delete pgcInfo_;
}
}
};
测试代码
#include "gc.h"
#include <string>
using namespace std;
void test(GCPtr<string>& gcpStr) {
GCPtr<string> t = gcpStr;
GCPtr<string> o(t);
cout << *o.GetPtr() << endl;
}
int main()
{
{
GCPtr<int> a(new int(9));
GCPtr<int> b(a);
GCPtr<int> c = a;
}
GCPtr<string> a(new string("this is a test"));
test(a);
vector<GCPtr<string>> v;
v.push_back(a);
v.push_back(new string("test2"));
cout << *((v.back()).GetPtr()) << endl;
return 0;
}