C.60:Makecopyassignmentnon-virtual,taketheparameterbyconst&,andreturnbynon-const&
C.60:拷貝賦值運(yùn)算符應(yīng)該是以const&為參數(shù),返回非常量引用類型的非虛函數(shù)
Reason(原因)
Itissimpleandefficient.Ifyouwanttooptimizeforrvalues,provideanoverloadthattakesa&&(seeF.18).
因?yàn)檫@樣簡(jiǎn)單且高效。如果你希望對(duì)右值優(yōu)化,提供一個(gè)使用&&(右值引用)的重載。
Example(示例)
classFoo{public:Foo&operator=(constFoo&x){//GOOD:noneedtocheckforself-assignment(otherthanperformance)autotmp=x;swap(tmp);//seeC.83return*this;}//...};Fooa;Foob;Foof();a=b;//assignlvalue:copya=f();//assignrvalue:potentiallymove
Note(注意)
Theswapimplementationtechniqueoffersthestrongguarantee.
實(shí)現(xiàn)交換函數(shù)(參考C.83)的技術(shù)提供了(不會(huì)發(fā)生自拷貝,譯者注)強(qiáng)有力的保證。
Example(示例)
Butwhatifyoucangetsignificantlybetterperformancebynotmakingatemporarycopy?ConsiderasimpleVectorintendedforadomainwhereassignmentoflarge,equal-sizedVectorsiscommon.Inthiscase,thecopyofelementsimpliedbytheswapimplementationtechniquecouldcauseanorderofmagnitudeincreaseincost:
但是能不能通過少進(jìn)行一次臨時(shí)的拷貝動(dòng)作來得到明顯更高的性能呢?考慮用于(元素,譯者注)大小相同的巨大Vector賦值的簡(jiǎn)單的Vector的場(chǎng)景。在這種情況下,通過swap技術(shù)實(shí)現(xiàn)的元素拷貝動(dòng)作將引起成本的大幅度增加。
譯者注
前面的例子,在swap之前進(jìn)行了一次拷貝構(gòu)造
template<typenameT>classVector{public:Vector&operator=(constVector&);//...private:T*elem;intsz;};Vector&Vector::operator=(constVector&a){if(a.sz>sz){//...usetheswaptechnique,itcan'tbebettered...return*this;}//...copyszelementsfrom*a.elemtoelem...if(a.sz<sz){//...destroythesurpluselementsin*thisandadjustsize...}return*this;}
Bywritingdirectlytothetargetelements,wewillgetthebasicguaranteeratherthanthestrongguaranteeofferedbytheswaptechnique.Bewareofself-assignment.
通過將數(shù)據(jù)直接寫入對(duì)象元素,我們可以得到基本的保證而不是通過swap技術(shù)提供的強(qiáng)保證。為了防止自己給自己賦值。
Alternatives(可選項(xiàng))
Ifyouthinkyouneedavirtualassignmentoperator,andunderstandwhythat'sdeeplyproblematic,don'tcallitoperator=.Makeitanamedfunctionlikevirtualvoidassign(constFoo&).Seecopyconstructorvs.clone().
如果你認(rèn)為你需要一個(gè)虛賦值操作運(yùn)算符,而且理解它會(huì)產(chǎn)生很深刻的問題,別把設(shè)計(jì)成賦值運(yùn)算符。將它定義為具名函數(shù),例如virtualvoidassign(constFoo&)。
拷貝構(gòu)造vs克隆的鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual
Enforcement(實(shí)施建議)
(Simple)Anassignmentoperatorshouldnotbevirtual.Herebedragons!(簡(jiǎn)單)賦值運(yùn)算符不應(yīng)該是虛函數(shù)。那樣做很危險(xiǎn)。
(Simple)AnassignmentoperatorshouldreturnT&toenablechaining,notalternativeslikeconstT&whichinterferewithcomposabilityandputtingobjectsincontainers.(簡(jiǎn)單)賦值運(yùn)算符應(yīng)該返回T&,這樣才能實(shí)現(xiàn)連續(xù)賦值。不要改成類似constT&的類型,這樣會(huì)影響組裝性并妨礙將對(duì)象放進(jìn)容器中。
(Moderate)Anassignmentoperatorshould(implicitlyorexplicitly)invokeallbaseandmemberassignmentoperators.Lookatthedestructortodetermineifthetypehaspointersemanticsorvaluesemantics.(中等)賦值運(yùn)算符應(yīng)該(隱式或顯式)調(diào)用所有的基類和成員的賦值運(yùn)算符。觀察析構(gòu)函數(shù)以決定這個(gè)類型式指針語義還是值語義。
以上就是深圳達(dá)內(nèi)教育Java培訓(xùn)機(jī)構(gòu)小編介紹的“JavaSE入門到精通視頻:賦值運(yùn)算符的三個(gè)注意事項(xiàng)”的內(nèi)容,希望對(duì)大家有幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。