手撕智能指针shareptr

智能指针是一个类,share_ptr采用引用计数器的方法,允许多个智能指针指向同一个对象,每当多一个指针指向该对象 时,指向该对象的所有智能指针内部的引用计数加1,每当减少一个智能指针指向对象时,引用计数会 减1,当计数为0的时候会自动的释放动态分配的资源。

知识点:

  1. delete m_ptr,m_ptr指向的地址所存目标被删除,该目标所占的堆空间也被删除,但是指针p本身没有被删除;

  1. 返回值为引用:share_ptr<T>&、T&,不需要创建无名临时对象,避免构造函数和析构函数的调用,从空间和时间上提高了程序执行的效率;

  1. 智能指针适用于各类型参数,所以要用T模板。

#include <iostream>
using namespace std;

template <typename T>
class share_ptr {
public:
    //1.构造函数
    share_ptr() : m_ptr(nullptr), m_count(new int(1)){}
    share_ptr(T* ptr) : m_ptr(ptr), m_count(new int(1)){}
    share_ptr(const share_ptr& P) : m_ptr(P.m_ptr), m_count(&(++(*P.m_count))){}
    //2.析构函数
    ~share_ptr() {
        if (--(*m_count) == 0) {
            delete m_ptr;
            delete m_count;
            cout << "source delete" << endl;
        }
    }
    //3.获得count计数值
    int getCount() {
        return *m_count;
    }
    //4.拷贝赋值重载
    share_ptr<T>& operator=(const share_ptr<T>& P) {
        if (this == &P) return *this;
        if (--(*m_count) == 0) {
            delete m_ptr;
            delete m_count;
            cout << "source delete" << endl;
        }
        m_ptr = P.m_ptr;
        m_count = P.m_count;
        (*m_count)++;
        return *this;
    }
    //5.重载*
    T& operator*() {
        return *m_ptr;
    }
    //6.重载->
    T* operator->() {
        return m_ptr;
    }

private:
    T* m_ptr;
    int* m_count;
};

测试代码:

int main() {
    share_ptr<int> p1(new int(1));
    cout << "p1 count的值:" << p1.getCount() << "  p1 m_ptr的值:" << *p1 << endl;

    share_ptr<int> p2(p1);
    cout << "p1 count的值:" << p1.getCount() << "  p1 m_ptr的值:" << *p1 << endl;
    cout << "p2 count的值:" << p2.getCount() << "  p2 m_ptr的值:" << *p2 << endl;

    share_ptr<int> p3(new int(5));
    cout << "p3 count的值:" << p3.getCount() << "  p3 m_ptr的值:" << *p3 << endl;
    
    p3 = p1;
    cout << "p1 count的值:" << p1.getCount() << "  p1 m_ptr的值:" << *p1 << endl;
    cout << "p2 count的值:" << p2.getCount() << "  p2 m_ptr的值:" << *p2 << endl;

    return 0;
}

测试结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值