c++中的常见泄漏(六)

-------------------------------------------------------------------------- 
*整理:Zsm。
*时间:2011-4-18。
*出处:http://blog.csdn.net/Zsm0107
--------------------------------------------------------------------------

缺少重载赋值运算符

详细:
    当赋值运算符左边的对象的内部地址和赋值右边运算符右边的对象的内部地址重叠时,内存泄露就发生了---左边的对象中的指针指向的内存已不再被引用,但是这块内存仍然没有释放。另外两个操作数对象指向了同一块动态分配的内存空间,当两个对象调用了析构函数释放同一块内存时就有可能造成堆得崩溃。

例子:
#include<iostream>
#include<string>
using namespace std;
class Point
{
private:
 int x;
 int y;
 char *color;
public:
    Point(int new_x , int new_y , char *col);
    //注意下面的拷贝构造函数,若缺失的有什么后果呢???:-)
    Point(const Point& rhs);
    const Point& operator=(const Point& rhs);
    ~Point();
    void print();
};

Point::Point(int new_x=0 , int new_y=0 , char *col="white")
{
 x=new_x;
 y=new_y;
 
 color=new char[strlen(col)+1];
 strcpy(color,col);

 cout<<"call constructor"<<endl;
}

Point::Point(const Point& rhs)
{
 x=rhs.x;
 y=rhs.y;
 color=new char[strlen(rhs.color)+1];
 strcpy(color,rhs.color);

 cout<<"call copy constructor"<<endl;
}

//这个函数允许将对象本身赋值给自己。将返回引用定义成const,使得重载的

//operate=返回值不能作为一个左值来使用。
const Point& Point::operator=(const Point& rhs)
{
 if(&rhs==this)
 {
  return (*this);
 }
 x=rhs.x;
 y=rhs.y;
 delete color;
 color=new char[strlen(rhs.color)+1];
 strcpy(color,rhs.color);
 
 cout<<"call operator="<<endl;
 return (*this);
}
Point::~Point()
{
 delete color;
 cout<<"call ~Point()"<<endl;
}

void Point::print()
{
 cout<<"I'm a point at ( "
  <<x<<" , "<<y<<" ) "<<endl
  <<"My color is: "<<color<<"."
  <<endl;
}

int main()
{
 Point p1(10,10,"Blue");
 Point p2(15,18,"white");

 Point p3=p2;  //隐式调用拷贝构造函数

 p1.print();
 p2.print();
 p3.print();

 p1=p2;
 p1.print();
 p2.print();

 return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值