码迷,mamicode.com
首页 > 其他好文 > 详细

类string的拷贝构造函数与赋值函数

时间:2016-04-04 17:50:47      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

    //参考高质量c++编程

复制构造函数

 1   String ::String (const String &other)
 2  {
 3  
 4 
 5      int length=strlen(other.m_date);    
 6                                          //other对象的字符长度,其不包括‘\0’
 7      m_data=new char[length+1];         
 8                                          //在堆上开辟一块内存,内存大小包括‘\0‘
 9     strcpy(m_data,  other.m_data);   
10    
11  }

 

赋值构造函数

 1  String &String operate=(const String &other)
 2  {
 3        if(this==&other)
 4               return *this;             //自赋值检测
 5       
 6       delete[] m_data;                  //清除原有内存
 7       int length=strlen(other.m_date);    
 8                                        //other对象的字符长度,其不包括‘\0’
 9       m_data=new char[length+1];         
10                                       //在堆上开辟一块内存,内存大小包括‘\0‘
11      strcpy(m_data,  other.m_data);   
12      
13     return *this;     
14  }

 

 

String a("hello");   //调用default构造函数。

String b=a;         //调用copy构造函数,初始化。

String c;

c=a;                  //调用赋值构造函数

 

当类中有指针数据成员,不能使用系统默认的复制构造函数和赋值构造函数。

      缺省的函数采用位复制,也就是仅仅赋值地址的内容, 也即意味着 执行c.m_data = a.m_data; 

其结果是:

            (1),c.m_data的原有内存没有释放    (没有执行delete[] m_data; 清除原有内存)

            (2),c与a的m_data指向同一块内存,改动一个会影响另一个。 (没有执行m_data=new char[length+1]; strcpy(m_data, other.m_data); )

            (3),当对象呗析构时,m_data被释放两次。

类string的拷贝构造函数与赋值函数

标签:

原文地址:http://www.cnblogs.com/shewell/p/5352293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!