一 拷貝構造函數是C++最基礎的概念之一,大家自認爲對拷貝構造函數了解麼?請大家先回答一下三個問題:
1. 以下函數哪個是拷貝構造函數,爲什麼?
- X::X(const X&);
- X::X(X);
- X::X(X&, int a=1);
- X::X(X&, int a=1, b=2);
2. 一個類中可以存在多於一個的拷貝構造函數嗎?
3. 寫出以下程序段的輸出結果, 並說明爲什麼? 如果你都能回答無誤的話,那麼你已經對拷貝構造函數有了相當的瞭解。
- #include
- #include
- struct X {
- template<typename T>
- X( T& ) { std::cout << "This is ctor." << std::endl; }
- template<typename T>
- X& operator=( T& ) { std::cout << "This is ctor." << std::endl; }
- };
- void main() {
- X a(5);
- X b(10.5);
- X c = a;
- c = b;
- }
解答如下:
1. 對於一個類X,如果一個構造函數的第一個參數是下列之一:
a) X&
b) const X&
c) volatile X&
d) const volatile X&
且沒有其他參數或其他參數都有默認值,那麼這個函數是拷貝構造函數.
- X::X(const X&); //是拷貝構造函數
- X::X(X&, int=1); //是拷貝構造函數
2.類中可以存在超過一個拷貝構造函數,
- class X {
- public:
- X(const X&);
- X(X&); // OK
- };
注意,如果一個類中只存在一個參數爲X&的拷貝構造函數,那麼就不能使用const X或volatile X的對象實行拷貝初始化.
- class X {
- public:
- X();
- X(X&);
- };
- const X cx;
- X x = cx; // error
如果一個類中沒有定義拷貝構造函數,那麼編譯器會自動產生一個默認的拷貝構造函數.
這個默認的參數可能爲X::X(const X&)或X::X(X&),由編譯器根據上下文決定選擇哪一個.
默認拷貝構造函數的行爲如下:
默認的拷貝構造函數執行的順序與其他用戶定義的構造函數相同,執行先父類後子類的構造.
拷貝構造函數對類中每一個數據成員執行成員拷貝(memberwise Copy)的動作.
a)如果數據成員爲某一個類的實例,那麼調用此類的拷貝構造函數.
b)如果數據成員是一個數組,對數組的每一個執行按位拷貝.
c)如果數據成員是一個數量,如int,double,那麼調用系統內建的賦值運算符對其進行賦值.
3. 拷貝構造函數不能由成員函數模版生成.
- struct X {
- template<typename T>
- X( const T& ); // NOT copy ctor, T can't be X
- template<typename T>
- operator=( const T& ); // NOT copy ass't, T can't be X
- };
原因很簡單, 成員函數模版並不改變語言的規則,而語言的規則說,如果程序需要一個拷貝構造函數而你沒有聲明它,那麼編譯器會爲你自動生成一個. 所以成員函數模版並不會阻止編譯器生成拷貝構造函數, 賦值運算符重載也遵循同樣的規則.(參見Effective C++ 3edition, Item45)
二 針對上面作者的討論,理解更深了,但是下面我還是會給出一個一般的標準的實現和注意事項:
#include "stdio.h"
#include <iostream>
#include <string>
struct Test1
{
Test1() { }
Test1(int i) { id = i; }
Test1(const Test1& test)
{
id = test.id;
}
Test1& operator = (const Test1& test)
{
if(this == &test)
return *this;
id = test.id;
return *this;
}
int id;
};
class Test2
{
public:
Test2(){ m_pChar = NULL;}
Test2(char *pChar) { m_pChar = pChar;}
Test2(int num)
{
m_pChar = new char[num];
for(int i = 0; i< num; ++i)
m_pChar[i] = 'a';
m_pChar[num-1] = '/0';
}
Test2(const Test2& test)
{
char *pCharT = m_pChar;
m_pChar = new char[strlen(test.m_pChar)];
strcpy(m_pChar, test.m_pChar);
if(!pCharT)
delete []pCharT;
}
Test2& operator = (const Test2& test)
{
if(this == &test)
return *this;
char *pCharT = m_pChar;
m_pChar = new char[strlen(test.m_pChar)];
strcpy(m_pChar, test.m_pChar);
if(!pCharT)
delete []pCharT;
return *this;
}
private:
char *m_pChar;
};
int main(int argc, char* argv[])
{
const Test1 ts(1); // Test1()
const Test1* p_ts = &ts;
const Test1 ts2(ts); //Test(const Test1& test)
const Test1 ts3 = ts; //Test(const Test1& test)
Test1 ts4; ts4 = ts; //Test1& operator = (const Test1& test)
Test2 t(5);
Test2 t2(t);
Test2 t3 = t2;
Test2 t4; t4 = t;
return 0;
}