自我实现C++智能指针

实现c++智能指针

代码展示

下面展示c++智能指针实现的代码

// An highlighted block
#include <iostream>
class RefBase{
private: 
    int count;
public:
    RefBase():count(0){};
    void incStrong(){ count++; };
    void decStrong(){ count--; };
    int getStrongCount(){ return count;};
};
class Person:public RefBase
{
public:
     Person()
     {
         std::cout<<"Person()"<<std::endl;
     }
     ~Person()
     {
         std::cout<<"~Person()"<<std::endl;
     }
     void print_inf(void)
     {
       std::cout<<"this is a test function!"<<std::endl;
    }
};
template<typename T>
class sp{
private:
     T *p;
public:
     sp() : p(0) {}
     sp( T* other )
     {
        std::cout<<"sp( Person* other )"<<std::endl;
        p = other;
        p->incStrong();
     } 
     sp( const sp &other )
     {
        std::cout<<"p( const sp &other )"<<std::endl;
        p = other.p;
        p->incStrong();
     } 
     ~sp(){
       if (p){
          std::cout<<"~sp()"<<std::endl;
          p->decStrong();
          if (p->getStrongCount() == 0)
          {
              delete p ;
              p = NULL;
          }
       }
     }
     T *operator->()
     {
         return p;
     }
     T& operator*()
     {
        return *p;
     }
};
template<typename T>
void test( sp<T> &other )
{
    sp<T> s =  other;
    std::cout<<"In test fuction"<<s->getStrongCount()<<std::endl;
    s->print_inf();
}
void main()
{
    //减少Person*指针;用sp替代person*
    sp<Person> other = new Person();
    std::cout<<"before test function"<<other->getStrongCount()<<std::endl;
    test(other);
}

代码分析

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值