手写智能指针

梳理智能指针实现功能:

1.创建对象——构造函数

2.回收对象——析构函数

3.拷贝构造

4.赋值重载操作符

5.引用计数(智能指针引用计数是线程安全的,我们实现的话可以使用atomic原子访问)

6.get方法

#include<iostream>
using namespace std;

#include<memory>

class AAAA{
private:
    string s;
public:
    AAAA(const string str)
    {
        s = str;
        cout<<"AAAA:"<< s << endl;
    }
    ~AAAA()
    {
        cout<<"~AAAA" << endl;
    }
    void say()
    {
        cout<<"say:"<< s << endl;
    }
};

#include<atomic>
template<typename T>
//空间指针和引用计数的捆绑关系
struct Node
{
    Node(T* _ptr)
    {
        //接收外面来的空间
        ptr = _ptr;
        nCount = 1;
    }
    ~Node()
    {
        //要回收空间
        delete ptr;
        nCount = 0;
    }
    T* ptr;
    //int nCount;
    atomic<int>nCount;
};

template<typename T>
class MyShared_ptr
{
public:
    //有参构造 正常使用是第一个指向这个空间的
    MyShared_ptr(T* _ptr)
    {
        m_ptr_count = new Node<T>( _ptr);
    }
    //拷贝构造 用已有对象来初始化该对象
    MyShared_ptr(const MyShared_ptr& _ptr)
    {
        m_ptr_count = _ptr.m_ptr_count;
        (m_ptr_count->nCount)++;
    }
    //析构 该对象回收 引用计数-1 如果归0 要回收空间
    ~MyShared_ptr()
    {
        if(m_ptr_count)
            (m_ptr_count->nCount)--;
        if(m_ptr_count->nCount == 0)
        {
            delete m_ptr_count;
            m_ptr_count = nullptr;
        }
    }
    //赋值操作符 原空间引用计数-1 如果归0 要回收空间 新空间引用计数+1
    const MyShared_ptr& operator = (const MyShared_ptr& _ptr)
    {
        if(this == &_ptr)return *this;//自己不能给自己赋值
        if(m_ptr_count)
        {
            (m_ptr_count->nCount)--;
            if(m_ptr_count->nCount == 0)
            {
                delete m_ptr_count;
            }
            m_ptr_count = _ptr.m_ptr_count;
            (m_ptr_count->nCount)++;
        }
        return *this;
    }
    //get()
    T* get()
    {
        if(m_ptr_count)
            return m_ptr_count->ptr;
        return nullptr;
    }
    //引用计数
    int use_count()
    {
        if(m_ptr_count)
            return m_ptr_count->nCount.load();
        return 0;
    }
private:
    Node<T>* m_ptr_count;
};

int main()
{
    {
        MyShared_ptr<AAA1A>spa(new AAAA("my shared_ptr a"));
        {
            //MyShared_ptr<AAAA>spb(new AAAA("my shared_ptr b"));
            MyShared_ptr<AAAA>spb = new AAAA("my shared_ptr b");
            spa = spb;
            cout<<"a use count:"<<spa.use_count()<<endl;
        }
        cout<<"a use count:"<<spa.use_count()<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值