简易实现shared_ptr智能指针

shared_ptr智能指针与auto_ptr智能指针不同的是,拷贝构造或赋值后,原来的指针仍然能够使用。
原因是这种指针用一个引用计数来计算有多少个指针指向同一个空间,拷贝构造和赋值,都会让计数+1,智能指针析构的时候计数-1,计数为0才释放内存。所以根据这几点可以自己实现shared_ptr智能指针的功能。

#include <iostream>
using namespace std;
template<typename T>
class mshared_ptr{
    T* ptr;
   /* int count;//不能用普通变量来保存计数,因为const对象无法修改
   成员变量*/
    int *count;//办法是用指针

    public:
    //构造
    mshared_ptr(T *_ptr=NULL):ptr(_ptr)
    {
        count=new int(0);
        if(ptr!=NULL)
            *count=1;
    }
    //拷贝构造
    mshared_ptr(const mshared_ptr &r)
    {
        cout<<"拷贝构造"<<endl;
        ptr=r.ptr;//让两个指针指向同一个地方
        count=r.count;//让count指针和原来的指向同一个地方
        ++*r.count;//原来的对象的引用计数++
    }
    //赋值运算符重载
    mshared_ptr &operator=(const mshared_ptr &r)
    {
        if(--*count==0)
        {
            delete ptr;
            delete count;
            cout<<"赋值重载中释放内存"<<endl;
        }
        ptr=r.ptr;
        count=r.count;
        ++*r.count;
        return *this;
    }
    //解引用
    T operator*()
    {
        return *ptr;
    }
    //析构
    ~mshared_ptr()
    {
        if(--*count==0)
        {
            delete ptr;
            delete count;
            cout<<"析构中释放内存"<<endl;
        }
    }
    //引用计数
    int use_count()
    {
        return *count;
    }
};

int main(void)
{
    mshared_ptr<double> ptr(new double(3.14));
    cout<<*ptr<<endl;
    // {
        mshared_ptr<double> ptr1=ptr;
        cout<<*ptr<<endl;
        cout<<*ptr1<<endl;
        cout<<"引用计数是"<<ptr.use_count()<<
            "\t"<<ptr1.use_count()<<endl;
    // }
    // cout<<"ptr1删除后ptr引用计数是"<<ptr.use_count()<<endl;

    mshared_ptr<double> ptr_n1(new double(1.59));
    ptr_n1=ptr;/*在让ptr_n1指向新的空间之前,ptr_n1原来的空间的
    引用计数要-1,如果为0要清除*/
    cout<<"赋值给ptr_n1后引用计数是"<<ptr.use_count()<<endl;

}


这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章