zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    python3编写网络爬虫18-代理池的维护
    python3编写网络爬虫17-验证码识别
    python3编写网络爬虫16-使用selenium 爬取淘宝商品信息
    python3编写网络爬虫15-Splash的使用
    python3编写网络爬虫14-动态渲染页面爬取
    LeetCode959 由斜杠划分区域(Java并查集)
    编译原理--语法分析之LR分析法的简单实现
    VsCode背景图片设置
    编译原理--基于Lex的词法分析器实验
    HDFS常用的shell命令
  • 原文地址:https://www.cnblogs.com/itdef/p/6144513.html
Copyright © 2011-2022 走看看