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