国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

C++對象的拷貝與賦值操作

2019-11-17 05:25:48
字體:
供稿:網(wǎng)友
我發(fā)現(xiàn)一些同事在編寫一個類時,知道什么時候需要實現(xiàn)拷貝構(gòu)造函數(shù)和賦值操作,但不知道什么時候拷貝構(gòu)造函數(shù)被調(diào)用,什么時候賦值操作被調(diào)用,甚至把二者混為一談。
要弄明白這個問題,最簡單的做法莫過于寫個測試程序試一下。不過那樣做也未必是好辦法,實驗的結(jié)果往往導(dǎo)致以偏概全的結(jié)論。不如好好想一下,弄清楚其中的原理,再去寫程序去驗證也不遲。
拷貝構(gòu)造函數(shù),顧名思義,等于拷貝+ 構(gòu)造。它肩負著創(chuàng)建新對象的任務(wù),同時還要負責(zé)把另外一個對象拷貝過來。比如下面的情況就調(diào)用拷貝構(gòu)造函數(shù):CString str = strOther;
賦值操作則只含有拷貝的意思,也就是說對象必須已經(jīng)存在。比如下面的情況會調(diào)用賦值操作。str = strOther;
   不過有的對象是隱式的,由編譯器產(chǎn)生的代碼創(chuàng)建,比如函數(shù)以傳值的方式傳遞一個對象時。由于看不見相關(guān)代碼,所以不太輕易明白。不過我們稍微思考一下,就會想到,既然是根據(jù)一個存在的對象拷貝生成新的對象,自然是調(diào)用拷貝構(gòu)造函數(shù)了。
兩者實現(xiàn)時有什么差別呢?我想有人會說,沒有差別。呵,假如沒有差別,那么只要實現(xiàn)其中一個就行了,何必要兩者都實現(xiàn)呢?不繞圈子了,它們的差別是:
    拷貝構(gòu)造函數(shù)對同一個對象來說只會調(diào)用一次,而且是在對象構(gòu)造時調(diào)用。此時對象本身還沒有構(gòu)造,無需要去釋放自己的一些資源。而賦值操作可能會調(diào)用多次,你在拷貝之前要釋放自己的一些資源,否則會造成資源泄露。
   明白了這些道理之后,我們不防寫個測試程序來驗證一下我們的想法:
#include <stdio.h>
#include <STDLIB.H>
#include <string.h>
classCString
{
public:
CString();
CString(constchar* pszBuffer);
~CString();
CString(constCString& other);
constCString& Operator=(constCString& other);
PRivate:
char* m_pszBuffer;;
};
CString::CString()
{
printf("CString::CString/n");
m_pszBuffer= NULL;
return;
}
CString::CString(constchar* pszBuffer)
{
printf("CString::CString(const char* pszBuffer)/n");
m_pszBuffer= pszBuffer!= NULL? strdup(pszBuffer) : NULL;
return;
}
CString::~CString()
{
printf("%s/n", __func__);
deletem_pszBuffer;
m_pszBuffer= NULL;
return;
}
CString::CString(constCString& other)
{
if(this== &other)
{
return;
}
printf("CString::CString(const CString& other)/n");
m_pszBuffer= other.m_pszBuffer!= NULL? strdup(other.m_pszBuffer) : NULL;
}
constCString& CString::operator=(constCString& 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;
}
voidtest(CStringstr)
{
CStringstr1= str;
return;
}
intmain(intargc, char* argv[])
{
CStringstr;
CStringstr1= "test";
CStringstr2= str1;
str1= str;
CStringstr3= str3;
test(str);
return0;
}原文地址:http://dev.csdn.net/author/absurd/082775af05e44a4db1e9cdb4977687b2.Html


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 三河市| 宁陕县| 星子县| 屯门区| 肇源县| 红桥区| 任丘市| 天柱县| 武隆县| 平和县| 克拉玛依市| 林口县| 广汉市| 车险| 潞城市| 潢川县| 班戈县| 石景山区| 缙云县| 天峻县| 尼勒克县| 青冈县| 南岸区| 郎溪县| 东乌珠穆沁旗| 东乡| 岢岚县| 宜良县| 长阳| 郧西县| 井研县| 灵川县| 尼玛县| 库伦旗| 曲阜市| 会泽县| 凌云县| 乌拉特中旗| 漠河县| 玉林市| 革吉县|