C++智能指针的入门

  C++98有智能指针了,但是到C++11上才大量的应用。啥为智能指针,其实智能指针就是个类,它直接来管理我们创建对象内存的释放,这样就能防止在写C++代码时,new出了一个对象,但是后面却没有delete。

  智能指针为一个类的话,那么这个类就重载有指针的操作符 ”  *     -> “,下面是个智能指针一个简单的实现,来进入智能指针的入门。

  代码如下:

  class Student
  {
    public:
      Student(string name)
      {
        this->name=name;
      }
      ~Student()
      {
        cout<<"Student delete!\n";
      }
      void showName()
      {
        cout<<"Student Name is :"<<name<<endl;
      }
    private:
      string name;
  };

  //Student类中有个成员name,还有个showName的函数。

    //SmartPoint就是智能指针类,它重载了“ * ” 和“ -> ”

、 class SmartPoint
  {
  public:
    SmartPoint(Student *p)        //作为智能指针的话,那么这里就要传入Student对应的指针
    {
      this->p=p;
    }
    ~SmartPoint()
    {
      if(this->p!=NULL)                //释放掉内部成员Student  *p指向的内存空间
      {
        cout<<"delete smartpoint\n";
        delete this->p;
      }
    }
    Student * operator->()     //重载  “  ->  “
    {
      return this->p;
    }
    Student & operator*()     //重载  “  *  “
    {
      return *this->p;
    }
  private:
    Student *p;       ///Student  作为成员变量
  };

  int main()
  {
    cout<<"start run\n";
    SmartPoint p1(new Student("tongtong"));     //p1就相当智能指针,指向了开辟出来的一个对象student
    p1->showName();
    return 0;
  }

  代码的运行结果如下:

  

posted @ 2021-02-06 01:51  田大叔  阅读(77)  评论(0)    收藏  举报