• c++垃圾回收代码练习 引用计数


    学习实践垃圾回收的一个小代码

    采用引用计数

     每次多一个指针指向这个分配内存的地址时候 则引用计数加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;
    }

  • 相关阅读:
    OPC客户端的进程安全初始化
    [精华] Oracle安装(linux)总结一下[转]
    Linux防火墙iptables的设置与启动[转]
    Linux Server 5.5安装SVN+Apache服务[转]
    Red hat Linux Enterprise 5.4 Edtion 学习笔记[二]
    RedHat Linux 5企业版开启VNCSERVER远程桌面功能[转]
    Linux服务配置:Vsftp的基本配置[转]
    Linux查看和剔除当前登录用户
    Ubuntu10.04的中文问题汇集与解决[转]
    Linux下扩展swap分区的方法
  • 原文地址:https://www.cnblogs.com/itdef/p/6144513.html
Copyright © 2020-2023  润新知