baidu_34602556 2016-06-21 13:54 采纳率: 16.7%
浏览 1147

请问哪位大神帮我看看这个简陋版的c++垃圾回收站,错在哪里啊?



#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;
}
  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?