美文网首页
十三、->和*重载,智能指针auto_ptr

十三、->和*重载,智能指针auto_ptr

作者: 木鱼_cc | 来源:发表于2018-06-07 16:44 被阅读0次

常规意义上讲,new 或是 malloc 出来的堆上的空间,都需要手动 delete 和 free 的。但在其它高级语言中,只需申请无需释放的功能是存在的。
c++中也提供了这样的机制。我们先来探究一下实现原理。

类名& operator*() {
    函数体
}

类名* operator-­‐>(){
    函数体
}

#include <memory>
class A{
public:
   A(){
         cout<<"A()....."<<endl;
      }
   ~A(){
         cout<<"~A()...."<<endl;
      }
   void func(){
         cout<<"a--->func()...."<<endl;
     }
};

class MyAutoPtr
{
   public:
      //有参构造函数,将A的对象地址接收过来
       MyAutoPtr(A *ptr)
       {
            this->m_p = ptr;
       }

      ~MyAutoPtr()
       {
          if(this->m_p != NULL)delete (this->m_p);
       }

      A* operator->()
       {
             return this->m_p;
       }

     A& operator*()//必须是返回引用,如果只返回A,就是返回匿名对象,调用func,也是这个匿名对象的调用,和m_p无关!
     {
           return *(this->m_p);
     }

   private:
      A *m_p;//指向A对象的地址
};

void test1(){
   
   auto_ptr<A> auto_p(new A);
//智能指针,可以给它new一块内存,但不需要释放
//<A>代表指向A类型的指针   
//new A表示开辟内存,固定语法

 /*
  A* ap = new A;
  ap->func();
  delete ap;
*/

   auto_p->func();//不需要delete

}


void test2()
{
    MyAutoPtr auto_p(new A);//自定义智能指针,调用有参构造函数,但是并不支持->(因为不是指针,实际是个对象)

    //上面就是auto_p = &A;
    //

    auto_p->func();//->需要重构!
    (*auto_p).func();//*需要重构(*m_p).func()
}


int main(void){

  

   test2();

   return 0;
}



相关文章

网友评论

      本文标题:十三、->和*重载,智能指针auto_ptr

      本文链接:https://www.haomeiwen.com/subject/nhpgsftx.html