您现在的位置: 中国男护士网 >> 考试频道 >> 计算机等级 >> 二级辅导 >> C十十 >> 辅导 >> 正文    
  计算机等级考试二级:C++对象的拷贝与赋值操作 【注册男护士专用博客】          

计算机等级考试二级:C++对象的拷贝与赋值操作

www.nanhushi.com     佚名   不详 

  我发现一些同事在编写一个类时,知道什么时候需要实现拷贝构造函数和赋值操作,但不知道什么时候拷贝构造函数被调用,什么时候赋值操作被调用,甚至把二者混为一谈。

  要弄明白这个问题,最简单的做法莫过于写个测试程序试一下。不过那样做也未必是好办法,实验的结果往往导致以偏概全的结论。不如好好想一下,弄清楚其中的原理,再去写程序去验证也不迟。

  拷贝构造函数,顾名思义,等于拷贝 + 构造。它肩负着创建新对象的任务,同时还要负责把另外一个对象拷贝过来。比如下面的情况就调用拷贝构造函数:
CString str = strOther;

  赋值操作则只含有拷贝的意思,也就是说对象必须已经存在。比如下面的情况会调用赋值操作。
str = strOther;

  不过有的对象是隐式的,由编译器产生的代码创建,比如函数以传值的方式传递一个对象时。由于看不见相关代码,所以不太容易明白。不过我们稍微思考一下,就会想到,既然是根据一个存在的对象拷贝生成新的对象,自然是调用拷贝构造函数了。

  两者实现时有什么差别呢?我想有人会说,没有差别。呵,如果没有差别,那么只要实现其中一个就行了,何必要两者都实现呢?不绕圈子了,它们的差别是:

  拷贝构造函数对同一个对象来说只会调用一次,而且是在对象构造时调用。此时对象本身还没有构造,无需要去释放自己的一些资源。而赋值操作可能会调用多次,你在拷贝之前要释放自己的一些资源,否则会造成资源泄露。

  明白了这些道理之后,我们不防写个测试程序来验证一下我们的想法:

#include
#include
#include

class CString
{  
public:
    CString();
    CString(const char* pszBuffer);
    ~CString();
    CString(const CString& other);
    const CString& operator=(const CString& other);

private:
    char* m_pszBuffer;;
}; 

CString::CString()
{
    printf("CString::CString\n");
    m_pszBuffer = NULL;
    return;
}  
CString::CString(const char* pszBuffer)
{
    printf("CString::CString(const char* pszBuffer)\n");
    m_pszBuffer = pszBuffer != NULL ? strdup(pszBuffer) : NULL;
    return;
}

CString::~CString()
{
    printf("%s\n", __func__);
    delete m_pszBuffer;
    m_pszBuffer = NULL;
    return;
}

CString::CString(const CString& other)
{
    if(this == &other)
    {
        return;
    }
    printf("CString::CString(const CString& other)\n");
    m_pszBuffer = other.m_pszBuffer != NULL ? strdup(other.m_pszBuffer) : NULL;
}

const CString& CString::operator=(const CString& other)
{
    printf("const CString& CString::operator=(const CString& other)\n");
    if(this == &other)
    {
        return *this;
    }
    if(m_pszBuffer != NULL)
    {
        free(m_pszBuffer);
        m_pszBuffer = NULL;
    }
         m_pszBuffer = other.m_pszBuffer != NULL ? strdup(other.m_pszBuffer) : NULL;
    return *this;
}

void test(CString str)
{
    CString str1 = str;
    return;
}

int main(int argc, char* argv[])
{
    CString str;
    CString str1 = "test";
    CString str2 =  str1;
    str1 = str;
    CString str3 = str3;
    test(str);
    return 0;
}

 

文章录入:杜斌    责任编辑:杜斌 
  • 上一篇文章:

  • 下一篇文章:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
     

    联 系 信 息
    QQ:88236621
    电话:15853773350
    E-Mail:malenurse@163.com
    免费发布招聘信息
    做中国最专业男护士门户网站
    最 新 热 门
    最 新 推 荐
    相 关 文 章
    没有相关文章
    专 题 栏 目

      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)                            【进男护士社区逛逛】
    姓 名:
    * 游客填写  ·注册用户 ·忘记密码
    主 页:

    评 分:
    1分 2分 3分 4分 5分
    评论内容:
  • 请遵守《互联网电子公告服务管理规定》及中华人民共和国其他各项有关法律法规。
  • 严禁发表危害国家安全、损害国家利益、破坏民族团结、破坏国家宗教政策、破坏社会稳定、侮辱、诽谤、教唆、淫秽等内容的评论 。
  • 用户需对自己在使用本站服务过程中的行为承担法律责任(直接或间接导致的)。
  • 本站管理员有权保留或删除评论内容。
  • 评论内容只代表网友个人观点,与本网站立场无关。