更新時間:2020-02-26 09:23:31 來源:動力節(jié)點 瀏覽2342次
C.60:Makecopyassignmentnon-virtual,taketheparameterbyconst&,andreturnbynon-const&
C.60:拷貝賦值運算符應(yīng)該是以const&為參數(shù),返回非常量引用類型的非虛函數(shù)
Reason(原因)
Itissimpleandefficient.Ifyouwanttooptimizeforrvalues,provideanoverloadthattakesa&&(seeF.18).
因為這樣簡單且高效。如果你希望對右值優(yōu)化,提供一個使用&&(右值引用)的重載。
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.
實現(xiàn)交換函數(shù)(參考C.83)的技術(shù)提供了(不會發(fā)生自拷貝,譯者注)強(qiáng)有力的保證。
Example(示例)
Butwhatifyoucangetsignificantlybetterperformancebynotmakingatemporarycopy?ConsiderasimpleVectorintendedforadomainwhereassignmentoflarge,equal-sizedVectorsiscommon.Inthiscase,thecopyofelementsimpliedbytheswapimplementationtechniquecouldcauseanorderofmagnitudeincreaseincost:
但是能不能通過少進(jìn)行一次臨時的拷貝動作來得到明顯更高的性能呢?考慮用于(元素,譯者注)大小相同的巨大Vector賦值的簡單的Vector的場景。在這種情況下,通過swap技術(shù)實現(xiàn)的元素拷貝動作將引起成本的大幅度增加。
譯者注
前面的例子,在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ù)直接寫入對象元素,我們可以得到基本的保證而不是通過swap技術(shù)提供的強(qiáng)保證。為了防止自己給自己賦值。
Alternatives(可選項)
Ifyouthinkyouneedavirtualassignmentoperator,andunderstandwhythat'sdeeplyproblematic,don'tcallitoperator=.Makeitanamedfunctionlikevirtualvoidassign(constFoo&).Seecopyconstructorvs.clone().
如果你認(rèn)為你需要一個虛賦值操作運算符,而且理解它會產(chǎn)生很深刻的問題,別把設(shè)計成賦值運算符。將它定義為具名函數(shù),例如virtualvoidassign(constFoo&)。
拷貝構(gòu)造vs克隆的鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual
Enforcement(實施建議)
(Simple)Anassignmentoperatorshouldnotbevirtual.Herebedragons!(簡單)賦值運算符不應(yīng)該是虛函數(shù)。那樣做很危險。
(Simple)AnassignmentoperatorshouldreturnT&toenablechaining,notalternativeslikeconstT&whichinterferewithcomposabilityandputtingobjectsincontainers.(簡單)賦值運算符應(yīng)該返回T&,這樣才能實現(xiàn)連續(xù)賦值。不要改成類似constT&的類型,這樣會影響組裝性并妨礙將對象放進(jìn)容器中。
(Moderate)Anassignmentoperatorshould(implicitlyorexplicitly)invokeallbaseandmemberassignmentoperators.Lookatthedestructortodetermineifthetypehaspointersemanticsorvaluesemantics.(中等)賦值運算符應(yīng)該(隱式或顯式)調(diào)用所有的基類和成員的賦值運算符。觀察析構(gòu)函數(shù)以決定這個類型式指針語義還是值語義。
以上就是動力節(jié)點Java培訓(xùn)機(jī)構(gòu)小編介紹的“JavaSE入門到精通視頻:賦值運算符的三個注意事項”的內(nèi)容,希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務(wù)。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743