《Effective C++》 读书笔记之二 构造/析构/赋值运算
《Effective C++》 读书笔记之二 构造/析构/赋值运算
条款10:令赋值(assignment)操作符返回一个reference to *this。
例子:
Widget&operator=(constWidget&rhs){...return*this;//返回*this}
2016-11-03 09:36:00
条款11:在operator= 中处理“自我赋值”。
例子:
classWidget{...voidswap(Widget&rhs);//交换*this与rhs的数据...};//第一种合理安全的写法Widget&Widget::operator=(constWidget&rhs){BitMap*pOrg=pb;//记住原先的pbpb=newBitMap(*rhs.pb);//令pb指向*pb的一个复件(副本)deletepOrg;//删除原先的pbreturn*this;}//第二种合理安全的写法Widget&Widget::operator=(constWidget&rhs){Widgettemp(rhs);swap(temp);return*this;}
重点:
确保当对象自我赋值时operator= 有良好行为。其中技术包括比较“来源对象”与“目标对象”的地址、精心周到的语句顺序、以及copy-and-swap。
确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。
2016-11-03 10:23:50
条款12:复制对象时勿忘其每一个成分。Copy all parts of an object.
例子:
voidlogCall(conststd::string&funcName);classCustomer{public:Customer(constCustomer&rhs);.Customer&operator=(constCustomer&rhs);private:std::stringname;};Customer::Customer(constCustomer&rhs):name(rhs.name)//复制所有成员,防止局部拷贝(partialcopy){logCall("Customercopyconstructor");}Customer&Customer::operator=(constCustomer&rhs){logCall("Customercopyassignmentoperator");name=rhs.name;return*this;}classPriorityCustmer:publicCustmer//一个derivedclass{public:PriorityCustomer(constPriorityCustomer&rhs);PriorityCustomer&operator=(constPriorityCustomer&rhs);private:intpriority};PriorityCustomer::PriorityCustomer(constPriorityCustomer&rhs):Customer(rhs),//调用baseclass的copy构造函数,如果不调用,会调用Customer的default构造函数priority(rhs.priority){logCall("PriorityCustomercopyconstructor");}PriorityCustomer&PriorityCustomer::operator=(constPriorityCustomer&rhs){logCall("PriorityCustomercopyassignmentoperator");Customer::operator=(rhs);//对baseclass成分进行赋值动作priority=rhs.priority;return*this;}
重点:
Copying函数应该确保复制“对象内的所有成员变量”及“所有base class成分”。
不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,比如init(),并由两个copying函数共同调用。
2016-11-03 11:20:20
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。