--------------------------------------------------------------------------
*整理: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;
}