復(fù)制構(gòu)造函數(shù)的函數(shù)名為類的名字,無返回值,和構(gòu)造函數(shù)的區(qū)別就在于形參的不同。復(fù)制構(gòu)造函數(shù)的形參為同類類型的引用,并且通常限定為const的引用,如Person類的復(fù)制構(gòu)造函數(shù)的聲明為:
Person(const Person &p); //copy-constructor
復(fù)制構(gòu)造函數(shù)在執(zhí)行對象的復(fù)制操作時,涉及到兩種類型的復(fù)制——淺復(fù)制和深復(fù)制。淺復(fù)制就是將被復(fù)制對象的數(shù)據(jù)成員的值一一的復(fù)制給另一個對象,這里應(yīng)該注意的是復(fù)制的是數(shù)據(jù)成員直接存儲的值,而沒有復(fù)制這個對象關(guān)聯(lián)的一些其它資源。比如:對象有一個指針類型的數(shù)據(jù)成員,這個指針指向的是另外的一塊內(nèi)存空間,所以這個指針直接存儲的值就是那塊內(nèi)存空間的地址,這個時候淺復(fù)制就只會復(fù)制指針存儲的地址值,而不會復(fù)制內(nèi)存空間存儲的值。然而,深復(fù)制就要求復(fù)制相應(yīng)的資源。
#include <iostream>
using namespace std;
struct Test {
//default-constructor
Test()
:pstr(new string) { }
//copy-constructor
#ifdef COPY
Test(const Test &nn);
#endif
void setVal(string ps);
void getVal(void) const;
private:
string *pstr;
};
#ifdef COPY
Test::Test(const Test &nn)
{
//new operate a new memory space
pstr = new string(*(nn.pstr));
}
#endif
void Test::setVal(string ps)
{
*pstr = ps;
}
void Test::getVal(void) const
{
cout << *pstr << endl;
}
int main(void)
{
Test n1;
n1.setVal("n1-set");
cout << "before creating n2, n1 ->";
n1.getVal();
Test n2 = n1;
n2.setVal("n2-set");
cout << "after creating n2, n1->";
n1.getVal();
cout << "after creating n2, n2->";
n2.getVal();
return 0;
}
上述程序在定義了COPY的時候運行結(jié)果為:
before creating n2, n1 ->n1-set
after creating n2, n1 ->
n1-setafter creating n2, n2 ->n2-set
這種結(jié)果就是深復(fù)制導(dǎo)致的,n1,n2兩個對象的數(shù)據(jù)成成員pstr指向了兩個不同的內(nèi)存空間。
沒有定義COPY的時候運行結(jié)果為:
before creating n2, n1 ->n1-set
after creating n2, n1 ->
n2-set
after creating n2, n2 ->n2-set
這種結(jié)果就是淺復(fù)制導(dǎo)致的,n1, n2兩個對象的數(shù)據(jù)成員pstr指向的是同一個內(nèi)存空間,他們共享同樣的數(shù)據(jù)。
注意:應(yīng)該避免淺復(fù)制,而應(yīng)該使用深復(fù)制。有指針等數(shù)據(jù)成員的時候,考慮自定復(fù)制構(gòu)造函數(shù)進(jìn)行深復(fù)制都是必要的。