Tải bản đầy đủ - 0 (trang)
None 27. Prefer the canonical forms of arithmetic and assignment operators

None 27. Prefer the canonical forms of arithmetic and assignment operators

Tải bản đầy đủ - 0trang

Summary

Ifyoua+b,alsoa+=b:Whendefiningbinaryarithmetic

operators,providetheirassignmentversionsaswell,andwrite

tominimizeduplicationandmaximizeefficiency.



Discussion

Ingeneral,forsomebinaryoperator@(beit+,-,*,andsoon),

youshoulddefineitsassignmentversionsuchthata@=band

a=a@bhavethesamemeaning(otherthanthatthefirst

formmightbemoreefficientandonlyevaluatesaonce).The

canonicalwayofachievingthisgoalistodefine@intermsof

@=,asfollows:

T&T::operator@=(constT&){

//implementation

return*this;

}

Toperator@(constT&lhs,constT&rhs){

Ttemp(lhs);

returntemp@=rhs;

}



Thetwofunctionsworkintandem.Theassignmentformdoes

theactualworkandreturnsitsleft-handparameter.Thenonassignmentversioncreatesatemporaryfromlhs,modifiesit

byinvokingtheassignmentform,andreturnsit.

Notethathereoperator@isanonmemberfunction,sothatit

willhavethedesirablepropertyofacceptingthesameimplicit

conversionsonitsleft-handsideandright-handside

parameters.(SeeItem44.)Forexample,ifyoudefineaclass

Stringthathasanimplicitconstructortakingachar,making

operator+(constString&,constString&)anonmember

enablesbothchar+StringandString+chartowork;a

memberversionString::operator+(constString&)would

onlyacceptthelatter.Anefficiency-mindedimplementation



mightchoosetodefineseveralnonmemberoverloadsof

operator@toavoidproliferationoftemporariesresulted

throughconversions(seeItem29).

Wherepossible,makeoperator@=anonmemberfunctionas

well(seeItem44).Inanycase,putallnonmemberoperatorsin

thesamenamespaceasTsothattheywillbeconveniently

availabletocallersaswellastoavoidnamelookupsurprises

(seeItem57).

Avariationistohaveoperator@acceptitsfirstparameterby

value.Thisway,youarrangeforthecompileritselftoperform

thecopyforyouimplicitly,andthiscangivethecompilermore

leewayinapplyingoptimizations:

T&operator@=(T&lhs,constT&rhs){

//implementation

returnlhs;

}



Toperator@(Tlhs,constT&rhs){//lhstakenbyva

returnlhs@=rhs;

}



Anothervariationistohaveoperator@returnaconstvalue.

Thistechniquehastheadvantagethatitdisablesnonsensical

codesuchasa+b=c,butitdoessoatthecostofdisabling

somepotentiallyusefulconstructssuchasa=(b+

c).replace(pos,n,d)expressivecodethat,inoneshot,

concatenatesstringsbandc,replacessomecharacters,and

assignsthefinalresulttoa.



Examples

Example:Animplementationof+=forstrings.When

concatenatingstrings,itisusefultoknowthelengthinadvance

soastoallocatememoryonlyonce.

String&String::operator+=(constString&rhs){

//implementation

return*this;

}



Stringoperator+(constString&lhs,constString&rhs){

Stringtemp;//initiallyempt

temp.Reserve(lhs.size()+rhs.size());//allocateenoug

return(temp+=lhs)+=rhs;//appendthestr

}



Exceptions

Insomecases(e.g.,operator*=oncomplexnumbers),an

operatormightmutateitsleft-handsidesosignificantlythatit

canbemoreadvantageoustoimplementoperator*=interms

ofoperator*ratherthanthereverse.



References

[Alexandrescu03a][Cline99]Đ23.06[Meyers96]Đ22

[Sutter00]Đ20



28.Preferthecanonicalformof++and--.

Prefercallingtheprefixforms

Summary

Discussion

Exceptions

References



Summary

Ifyou++c,alsoc++:Theincrementanddecrementoperators

aretrickybecauseeachhaspre-andpostfixforms,withslightly

differentsemantics.Defineoperator++andoperator--such

thattheymimicthebehavioroftheirbuilt-incounterparts.

Prefertocalltheprefixversionsifyoudon'tneedtheoriginal

value.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

None 27. Prefer the canonical forms of arithmetic and assignment operators

Tải bản đầy đủ ngay(0 tr)

×