条款12:复制对象时勿忘其每一个部分
設(shè)計(jì)良好的面向?qū)ο笙到y(tǒng)會將對象的內(nèi)部封裝起來,只留兩個(gè)函數(shù)負(fù)責(zé)對象拷貝,即copy構(gòu)造函數(shù)與copy assignment操作符。編譯器會在必要的時(shí)候?yàn)轭悇?chuàng)建coping函數(shù),并說明這些“編譯器生成版”的行為:將被拷貝對象的所有成員變量都做一份拷貝。
任何時(shí)候,只要自己實(shí)現(xiàn)派生類的copying函數(shù),則必須很小心的復(fù)制其基類成分。這些成分往往是private私有的,故無法直接訪問它們,因此應(yīng)該讓派送類的coping函數(shù)調(diào)用相應(yīng)的基類函數(shù):
?void logCall(const string& funcName);class Customer{public:
...Customer(const Customer& rhs);Customer& operator=(const Customer& rhs);
...private:string name;Date lastTranscation;};
class PriorityCustomer : public Customer{public:...PriorityCustomer(const PriorityCustomer& rhs);PriorityCustomer& operator=(const PriorityCustomer& rhs);...private:int priority;};PriorityCustomer ::PriorityCustomer (const PriorityCustomer& rhs) : Customer(rhs), //調(diào)用基類的copy構(gòu)造函數(shù)priority(rhs.priority){logCall("PriorityCustomer copy constructor");}PriorityCustomer& PriorityCustomer ::operator = (const PriorityCustomer& rhs) {logCall("PriorityCustomer copy assignment constructor");Customer::operator=(rhs); //對基類Customer成分進(jìn)行復(fù)制動作priority = rhs.priority;return *this;}
當(dāng)編寫一個(gè)copying函數(shù),確保1、復(fù)制所有l(wèi)ocal成員變量,2、調(diào)用所有基類的適當(dāng)?shù)腸opying函數(shù)。
注意兩個(gè)錯(cuò)誤用法:1、令copy assignment操作符調(diào)用copy構(gòu)造函數(shù)是錯(cuò)誤的,因?yàn)樵谶@就像試圖構(gòu)造一個(gè)已存在的對象。
2、令copy構(gòu)造函數(shù)調(diào)用copy assignment操作符同樣是錯(cuò)誤的。構(gòu)造函數(shù)用來出事后對象,而assignment操作符只實(shí)行與已初始化的對象身上。對一個(gè)尚未構(gòu)造好的對象賦值,就像在一個(gè)尚未初始化的對象身上做“z只對已初始化對象才有意義”的事意義。
消除copy構(gòu)造函數(shù)與copy assignment操作符重復(fù)代碼的做法是:建立一個(gè)新的成員函數(shù)給兩者調(diào)用。這樣的函數(shù)往往是private而且被命名為init。這個(gè)策略可以安全消除copy構(gòu)造函數(shù)與copy assignment操作符之間的代碼重復(fù)。
請牢記:
1、copying 函數(shù)應(yīng)該確保復(fù)制“對象內(nèi)的所有成員變量”及“所有基類成分”。
2、不要嘗試以某個(gè)copying函數(shù)實(shí)現(xiàn)另一個(gè)copying函數(shù)。應(yīng)該將共同機(jī)能放進(jìn)第三個(gè)函數(shù)中,并由兩個(gè)copying函數(shù)共同調(diào)用。
轉(zhuǎn)載于:https://www.cnblogs.com/lwenwen/p/3468569.html
總結(jié)
以上是生活随笔為你收集整理的条款12:复制对象时勿忘其每一个部分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaWeb -- Struts1 多
- 下一篇: 【转载】dotnet 线程同步