#include <list>
#include <iostream>
#include <typeinfo>
#include <cstdlib>
using namespace std;
//GCInfo 模板类为GClist的元素,包含具体地址及其引用计数
template <class T>
class GCInfo
{
public:
T*memptr;
unsigned int times;
GCInfo() //构造
{
memptr = NULL;
times = 0;
}
GCInfo(T*ptr)
{
memptr = ptr;
times = 0;
}
~GCInfo()
{
delete memptr;
}
};
//指针类,GCptr
template <class T,int size = 0>
class GCptr
{
public:
typename list<GCInfo<T>>::iterator
GCptr<T, size>::findPtrInfo(T*ptr);
T* operator=(T*ptr);
GCptr<T, size>& operator=(GCptr<T, size> new_gcptr);
void collect();
//重载解引用符
T& operator*()
{
return *addr;
}
T operator->()
{
return *addr;
}
static list <GCInfo<T>> gclist;
T*addr;
};
//findPtrInfo 在链表中寻找指定地址的元素是否存在
//存在返回iterator不存在返回尾
template<class T, int size = 0>
typename list<GCInfo<T>>::iterator
GCptr<T, size>::findPtrInfo(T*ptr)
{
list <GCInfo<T>>::iterator p;
for (p = gclist.begin(); p != gclist.end(); ++p)
if (p->memptr == ptr)return p;
return p;
}
//Gcptr 对象赋值 ‘=’重载
template<class T,int size>
T* GCptr<T, size>::operator=(T*ptr)
{
list<GCInfo<T>>::iterator p;
p = findPtrInfo(addr); //该指针失去对该内存所有权计数减一
p->times--;
p = findPtrInfo(ptr);
if (p == gclist.end())
{
GCInfo<T> new_gcinfo(ptr);
new_gcinfo.times++;
gclist.push_front(new_gcinfo);
}
else
{
p->memptr = ptr;
p->times++;
}
return ptr;
}
//=的右操作数,内存引用计数加一,赋值
template<class T, int size>
GCptr<T, size>& GCptr<T, size>::operator=(GCptr<T,size> new_gcptr)
{
list<GCInfo<T>>::iterator p;
p = findPtrInfo(addr);
p->times++;
new_gcptr.addr = addr;
}
template<class T, int size>
void GCptr<T, size>::collect()
{
list<GCInfo<T>>::iterator p;
for(p = gclist.begin();p != gclist.end();p++)
{
if (p->times == 0)
gclist.erase(p);
}
}
class a
{
int c;
int b;
};
int main()
{
a b;
a e;
a f;
GCptr<a> c;
c = &b;
c = &e;
c = &f;
c.collect();
return 0;
}