Tải bản đầy đủ - 0 (trang)
Chapter 55.  Prefer the canonical form of assignment

Chapter 55.  Prefer the canonical form of assignment

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

Summary

Yourassignment:Whenimplementingoperator=,preferthe

canonicalformnonvirtualandwithaspecificsignature.



Discussion

PrefertodeclarecopyassignmentforatypeTwithoneofthe

followingsignatures(see[Stroustrup00]and

[Alexandrescu03a]):



T&operator=(constT&);//classic

T&operator=(T);//potentiallyoptimizer-fri



Settleforthesecondversionifyouwouldneedtomakeacopy

oftheargumentinsideyouroperatoranyway,suchastheswapbasedidiomfeaturedinItem56.

Avoidmakinganyassignmentoperatorvirtual(see[Meyers96]

Đ33and[Sutter04]Đ19).Ifyouthinkyouneedvirtualbehavior

forassignment,rereadthosecitationsfirst.Ifthatdoesn't

dissuadeyouandyoustillthinkyouneedvirtualassignment,

prefertoprovideanamedfunctioninstead(e.g.,virtualvoid

Assign(constT&);).

Don'treturnconstT&.Althoughthishasthebenefitof

preventingoddcodelike(a=b)=c,ithasthedrawbackthatyou

wouldn'tbeabletoputTobjectsintostandardlibrary

containers;thecontainersrequirethatassignmentreturna

plainT&.

Alwaysmakecopyassignmenterror-safe,andprefertoprovide

thestrongguarantee.(SeeItem71.)

Ensuretheassignmentoperatorissafeforself-assignment.

Avoidwritingacopyassignmentoperatorthatreliesonacheck

forself-assignmentinordertoworkproperly;often,that

revealsalackoferrorsafety.Ifyouwritethecopyassignment

operatorusingtheswapidiom(seeItem56),itwill



automaticallybebothstronglyerror-safeandsafeforselfassignment;ifself-assignmentisfrequentduetoreference

aliasingorotherreasons,it'sokaytostillcheckforselfassignmentanywayasanoptimizationchecktoavoidneedless

work.

Explicitlyinvokeallbaseassignmentoperatorsandassignall

datamembers([Meyers97]Đ16);notethatswapping

automaticallytakecaresofallthesethings.Return*this

([Meyers97]Đ15).



References

[Alexandrescu03a][Cargill92]pp41-42,95[Cline99]

Đ24.01-12[Koenig97]Đ4[Meyers96]Đ33[Meyers97]Đ17

[Murray93]Đ2.2.1[Stroustrup00]Đ10.4.4.1,Đ10.4.6.3

[Sutter00]Đ13,Đ38,Đ41[Sutter04]Đ19



56.Wheneveritmakessense,providea

no-failswap(andprovideitcorrectly)

Summary

Discussion

Exceptions

References



Summary

swapisbothalightweightandaworkhorse:Considerproviding

aswapfunctiontoefficientlyandinfalliblyswaptheinternalsof

thisobjectwithanother's.Suchafunctioncanbehandyfor

implementinganumberofidioms,fromsmoothlymoving

objectsaroundtoimplementingassignmenteasilytoproviding

aguaranteedcommitfunctionthatenablesstronglyerror-safe

callingcode.(SeealsoItem51.)



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

Chapter 55.  Prefer the canonical form of assignment

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

×