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

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

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

缺少拷贝构造函数

详细:
    1.拷贝构造函数是以同类型对象的引用为参数的构造函数。

    2.如果一个对象赋给一个新的对象时,类中没有定义拷贝拷贝构造函数,编译器就会认为是以逐个成员拷贝的方式来复制数据成员。问题是:
      逐个成员拷贝的方式复制指针被定义为讲一个变量的地址复制给另一个变量。这种隐式复制的结果是了两个对象拥有指向同一个人动态分配的内存空间的指针。当释放第一个对象的时候,它的析构函数会释放与该对象有关的动态分配内存空间。而释放第二个对象的时候,它的析构函数将会再次释放相同的内存,所以可能造成堆的崩溃。

    3.隐式调用:当一个对象用同类型的对象来初始化时,会调用拷贝构造函数。或是用一个对象以值传递方式作为拷贝构造函数的参数,或是从一个函数中返回一个对象时都会调用拷贝构造函数。

例子:

#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);
    ~Point();
    Point duplicate(Point rhs);
    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;
}

Point::~Point()
{
 delete color;
 cout<<"call ~Point()"<<endl;
}

/*这个函数以值方式将一个Point对象作为函数的参数。这将造成隐式的调用拷贝构造函数。另外,因为这个函数以值方式返回一个Point对象,所以将隐式调用拷贝构造函数*/

Point Point::duplicate(Point rhs)
{
 x=rhs.x;
 y=rhs.y;
 
 color=new char[strlen(rhs.color)+1];
 strcpy(color,rhs.color);
 
 cout<<"call duplicate function"<<endl;
 return (*this);
}

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.duplicate(p2); //两次隐式调用拷贝构造函数

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

 return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值