C++语法基础--智能指针

1.智能指针准备知识:new关键字定义的指针,如果不用delete关键字删除,即使指针超出作用域范围,该指针也不会被删除
Example:
先给出一个在析构函数没有删除指针的类
 class A
 {
   public:
  A(int *pt):p(pt)
  {
  }
 
   private:
    int *p;
 };


  
 int main()
 {
     int *a=new int(1);
     {
     A b(a);
  }
 
  cout<<*a<<endl;
//1
    
   return 0;
 }


在A的析构函数中删除指针
class A
 {
   public:
     A(int *pt):p(pt)
      {
      }

 ~A()
   {
    delete p;

   }


   private:
    int *p;
 };


int main()
 {
     int *a=new int(1);
  {
  A b(a);
   }
 
  cout<<*a<<endl;
//随机数,因为对象b超出了作用域,自动调用了对象b的析构函数。
    
   return 0;
 }


2.实现智能指针基本步骤
  *复制构造函数将旧对象复制到新对象是,将记数加1
  *赋值操作符将左操作数的使用记数减1,并将右操作数的使用记数加1,如果左操作数的使用记数减至0,赋值操作符必须删除它所指向的对象

  *析构函数将使用记数减1,如果使用记数减至0,删除基础对象


       Tips:

              智能指针的关键在于设置一个类专用于保存指针。


注:绿色代码部分只是为了验证智能指针是否工作正常,并非智能指针类必须的
Example:
class count_pointer
{
friend class smart_pointer;
  private:
  count_pointer(int *p):pt(p),count(1)
  {

  }


  ~count_pointer()
  {
  cout<<"~count_pointer()"<<endl;

  }


  int *pt;
  int count;

};


class smart_pointer
{
   public:
    smart_pointer(int *pt):cp(new count_pointer(pt))
    {
    }
    
   smart_pointer(smart_pointer& other):cp(other.cp)
 {
     ++cp->count;

  }


smart_pointer& operator=(smart_pointer& other) 
 {
    ++other.cp->count;
    if(--cp->count==0)
     {
         delete cp;
      }
   cp=other.cp;
   return *this;

  }


 ~smart_pointer()
 {
  
 if(--cp->count==0)
   {
   delete cp;
   }

 }


    void print()
    {
       cout<<"count_pointer::count  "<<cp->count<<endl;
      cout<<"count_pointer::*pt  "<<*(cp->pt)<<endl;

    }


   private:
     count_pointer *cp;
};
 
  
 int main()
 {
  int *p=new int(100);
  smart_pointer sp1(p);
  cout<<"smart_pointer sp1:"<<endl;
  sp1.print();
  cout<<endl;
 
 smart_pointer sp2(sp1);
 cout<<"after using copy constructor:"<<endl;
 cout<<"smart_pointer sp1:"<<endl;
  sp1.print();
  cout<<endl;
 
  cout<<"smart_pointer sp2:"<<endl;
  sp2.print();
  cout<<endl;

  int *p1=new int(200);
  smart_pointer sp3(p1);

  sp1=sp3;

  cout<<"after using assign operator:"<<endl;

  cout<<"smart_pointer sp1:"<<endl;
  sp1.print();
  cout<<endl;
 
  cout<<"smart_pointer sp2:"<<endl;
  sp2.print();
  cout<<endl;
 
  cout<<"smart_pointer sp3:"<<endl;
  sp3.print();
  cout<<endl;

     return 0;
 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值