C++简单版shared_ptr智能指针的实现

sp_counted_base.h

#pragma once
class sp_counted_base//管理对象引用计数
{
public:
    sp_counted_base() :count(1)
    {
    }
    void add()
    {   
        count++;
    }
    void dec()
    {
        count--;
    }
    int getcount()
    {
        return count;
    }
    virtual void realse() = 0;
private:
    int count;
};

sp_counted_impl.h

#include "sp_counted_base.h"
template<typename T>
class sp_counted_impl : public sp_counted_base//管理对象释放
{
public:
    sp_counted_impl(T *p=NULL) :px(p){}
    void realse()
    {
        dec();
        if (getcount() == 0)
        {   
            if (px != NULL)
            {
                cout << "free" << endl;
                delete px;
                px = NULL;
            }
        }
    }
private:
    T *px;
};

shared_count.h

#pragma once
#include "sp_counted_base.h"
#include "sp_counted_impl.h"
template<typename T>
class shared_count
{
public:
    shared_count(T *ptr=NULL):pi(new sp_counted_impl<T>(ptr))
    {}
    shared_count(const shared_count &sc)
    {
        pi = sc.pi;
        pi->add();
    }
    shared_count& operator=(const shared_count& sc)
    {
        if (this != &sc)
        {
            pi = sc.pi;
            pi->add();//引用计数加1。
        }
        return *this;
    }
    ~shared_count()
    {
        realse();
    }
    void realse()
    {
        pi->realse();
    }
    void add()
    {
        pi->add();
    }
private:
    sp_counted_base *pi;
};

share_ptr.h

#pragma once
#include "shared_count.h"
template<typename T>
class shared_ptr//对象操作。
{
public:
    shared_ptr(T *ptr = NULL) :px(ptr), pn(ptr)
    {}
    shared_ptr(const shared_ptr& sp)
    {
        px = sp.px;
        pn = sp.pn;
    }
    shared_ptr& operator = (const shared_ptr& sp)
    {
        if (this != &sp)
        {
            pn.realse();//释放它原来所指的对象的引用。
            pn = sp.pn;//计数重载=,在shared_count.h中实现。
            px = sp.px;//重新指向对象。
        }
        return *this;
    }

    ~shared_ptr()
    {
    }
    T* operator->()
    {
        return px;
    }
    T& operator*()
    {
        return *px;
    }
private:
    T *px;
    shared_count<T> pn;
};

main.cpp//测试代码

#include <iostream>
#include "shared_ptr.h"
using namespace std;
int main()
{
    shared_ptr<int> ps(new int(1));
    shared_ptr<int> pb(ps);
    shared_ptr<int> pd(pb);
    shared_ptr<int> pq(pd);
    shared_ptr<int> pm(new int(2));
    pm = pq;
    return 0;
}

未涉及线程安全,未涉及weak_ptr,未涉及boost库里面的定置删除器/定置分配器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值