详解C++-(=)赋值操作符、智能指针编写分享!

(=)赋值操作符

(=)赋值操作符注意事项

首先要判断两个操作数是否相等

返回值一定是 return *this; 返回类型是Type&型,避免连续使用=后,出现bug

比如:

  class Test{      int *p;      Test(int i)      {         p=new int(i);      }      Test& operator = (const Test& obj)      {         if(this!=obj)         {             delete p;             p=new int(*obj.p);         }         return *this;      }  };

编译器默认提供的类函数

包括了:构造函数,析构函数,拷贝构造函数, (=)赋值操作符

智能指针

智能指针的由来

在以前C程序里,使用malloc()等函数动态申请堆空间时,若不再需要的内存没有被及时释放,则会出现内存泄漏,若内存泄漏太多,

则会直接导致设备停止运行,特别是嵌入式设备,可能有些设备一上电就要运行好几个月.

在C++里,为了减少内存泄漏,所以便引出了智能指针

介绍

注意

比如ptr->value的->:

当ptr的类型是普通指针类型时,等价于:(*ptr).mem

当ptr的类型是类时,等价于:(ptr.operator->())->value    等价于: ( *(ptr.operator->()) ).value

所以->操作符函数的返回类型是type*,返回值是一个指针变量本身(不带*)

接下来个示例,指向一个int型的智能指针

  #include <iostream>  using namespace std;  class Point{      int *p;  public:      Point(int *p=NULL)      {       this->p = p;      }      int* operator -> ()      {         return p;      }      int& operator *()      {         return *p;      }      ~Point()      {       cout<<"~Point()"<<endl;       delete p;      }  };  int main()  {          for(int i=0;i<5;i++)       {      Point p=new int(i);      cout <<*p<<endl;      }      return 0;  }

运行打印:

0
~Point()
1
~Point()
2
~Point()
3
~Point()
~Point()

从结果可以看到, Point p每被从新定义之前,便会自动调用析构函数来释放之前用过的内存,这样便避免了野指针的出现。

接下来,我们继续完善上面代码,使它能够被赋值.

  #include <iostream>  using namespace std;  class Point{      int *p;  public:      Point(int *p=NULL)      {       this->p = p;      }       bool isNULL()      {         return (p==NULL);      }      int* operator -> ()      {         return p;      }      int& operator *()      {         return *p;      }     Point& operator = (const Point& t)      {         cout<<"operator =()"<<endl;         if(this!=&t)         {             delete p;             p = t.p;             const_cast<Point&>(t).p=NULL;         }              return *this;      }      ~Point()      {       cout<<"~Point()"<<endl;       delete p;      }  };  int main()  {          Point p=new int(2);      Point p2;      p2= p;     //等价于 p2.operator= (p);       cout <<"p=NULL:"<<p.isNULL()<<endl;      *p2+=3;    //等价于 *(p2.operator *())=*(p2.operator *())+3;                //p2.operator *()返回一个int指针,并不会调用Point类的=操作符      cout <<"*p2="<<*p2 <<endl;      return 0;  }

运行打印:

operator =()      
p=NULL:1              // Point  p的成员已被释放
*p2=5
~Point()
~Point()

但是,还有个缺点,就是这个智能指针仅仅只能指向int类型,没办法指向其它类型.

总结

以上所述是小编给大家介绍的C++-(=)赋值操作符、智能指针编写,希望对大家有所帮助,如果大家有任何疑问请给我留

言,小编会及时回复大家的。在此也非常感谢大家对<计算机技术网(www.ctvol.com)!!>网站的支持!

—-想了解详解C++-(=)赋值操作符、智能指针编写分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/482323.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐