C++ 实现智能指针(带引用计数)




#include<bits/stdc++.h>
using namespace std;
//实现一个带引用计数的智能指针
/*
思路:对象有两个成员变量,一个成员变量指向资源,一个成员变量指向计数。(计数必须在堆上分配)
    构造函数:让资源指针指向资源,并且创建一个和这个资源配对的int=1。
    析构函数:判断int==0,决定是否释放资源
    拷贝构造:int++,_p指向同一个资源
    拷贝赋值运算符:检查自赋值,释放之前资源,赋值
    解引用*:返回引用T
    箭头:返回p指针、

*/

template<typename T>
class Cnt{
public:
    Cnt(T*p=NULL):_p(p){
        if(_p!=NULL){
            count=1;
        }else{
            count=0;
        }
    }
    int getcnt(){
        return count;
    }
    void sub(){
        count--;
    }
    void add(){
        count++;
    }
private :
    T *_p;
    int count;    
};

template<typename T>
class ssmart{
public:
    ssmart(T*p=NULL):_p(p),cnt(){//nullptr
        cnt= new Cnt<T>(_p);
    }
    ~ssmart(){
        if(cnt->getcnt()==1){
            delete cnt;
            delete _p;            
        }else{
            cnt->sub();
        }
    }
    ssmart(const ssmart&smart){
        _p=smart._p;
        cnt=smart.cnt;
        cnt->add();
    }
    ssmart& operator=(const ssmart&smart){

        if(this==smart)return *this;
        if(_p!=NULL){
            cnt->sub();
            if(!cnt->getcnt()){
                delete cnt;
                delete _p;                
            }
        }
        _p=smart._p;
        cnt->add();
        return *this;
    }
    T& operator*(){
        return *_p;
    }
    T& operator->(){
        return _p;
    }
private:
    T*_p;
    Cnt<T>* cnt;
};
int main(){
    ssmart<int> p(new int);
    *p=15;
    cout<<*p<<endl;
    ssmart<int> p1(p);
    cout<<*p1<<endl;
    return 0;
}
########################################################################################
1.29练习:
#include<bits/stdc++.h>
using  namespace std;

template<typename T>
class smart{
public :

    smart(T *p){
        _p=p;
        _cnt= new int(1);

        cout<<"ok"<<endl;
    }
    ~smart(){
        (*_cnt)--;
        if(*_cnt==0)delete _p;
    }
    smart(const smart&rhs){
        _cnt=rhs._cnt;
        (*_cnt)++;
        _p=rhs._p;
    }
    smart& operator=(const smart&rhs){
        if(&rhs==this)return *this;

        if(*_cnt-- == 1){
            delete _p;
        }

        _cnt=rhs._cnt;
        (*_cnt)++;
        _p=rhs._p;
        return *this;
    }

    int& operator*(){
        return *_p;
    }
    int* operator->(){
        return _p;
    }
    void show(){
        cout<<"cnt:"<< *_cnt<<"   "<<"p:"<< *_p <<endl;
    }
private :
    int *_cnt;
    T *_p;
};
int main(){
    int *p=new int(1100) ;
    smart<int> data(p);

    *data=100;
    cout<<*data<<endl;

    data.show();
    return 0;
}






































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值