智能指针实现C++

#include <iostream>

using namespace std;
template <typename T>
class Shared_ptr{
private:
    T* _ptr;
    size_t *_count;//unsigned int *_count;
public:
    Shared_ptr(T* ptr = nullptr):_ptr(ptr){
        if(_ptr){
            _count = new size_t(1);
        }else {
            _count = new size_t(0);
        }
    }
    Shared_ptr(const Shared_ptr& ptr){
        if(this !=  &ptr){
            this->_ptr = ptr._ptr;
            this->_count = ptr._count;
            (*this->_count)++;
        }
    }
    Shared_ptr&operator=(const Shared_ptr& ptr){
        if(this ->_ptr == ptr._ptr){
            return *this;
        }
        if(this->_ptr){
            (*this->_count)--;
            if(this->_count == 0){
                delete this->_ptr;
                delete this->_count;
            }
        }
        this->_ptr = ptr._ptr;
        this->_count = ptr._count;
        (*this->_count)++;
        return *this;
    }
    T& operator*(){
        assert(this->_ptr == nullptr);
        return *(this->_ptr);
    }
    T* operator->(){
        assert(this->_ptr == nullptr);
        return this->_ptr;
    }
    ~Shared_ptr(){
        (*this->_count)--;
        if(*this->_count == 0){
            delete this->_ptr;
            delete this->_count;
        }
    }
    size_t use_count(){
        return *this->_count;
    }
};

int main(){
    Shared_ptr<int>sp(new int(130));
    cout<<sp.use_count()<<endl;
    Shared_ptr<int>sp1(sp);
    cout<<sp1.use_count()<<endl;
    cout<<sp.use_count()<<endl;
    Shared_ptr<int>sp2(new int(23));
    sp1 = sp2;
    cout<<sp.use_count()<<endl;
    cout<<sp1.use_count()<<endl;
    cout<<sp2.use_count()<<endl;
}

智能指针功能说明:

  智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,构造函数减少引用计数(如果引用计数减至0,则删除基础对象)。智能指针就是模拟指针动作的类。所有的智能指针都会重载 -> 和 * 操作符。智能指针还有许多其他功能,比较有用的是自动销毁。这主要是利用栈对象的有限作用域以及临时对象(有限作用域实现)析构函数释放内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值