Tải bản đầy đủ - 0 (trang)
Chapter 44.  Prefer writing nonmember nonfriend functions

Chapter 44.  Prefer writing nonmember nonfriend functions

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

Summary

Avoidmembershipfees:Wherepossible,prefermaking

functionsnonmembernonfriends.



Discussion

Nonmembernonfriendfunctionsimproveencapsulationby

minimizingdependencies:Thebodyofthefunctioncannot

cometodependonthenonpublicmembersoftheclass(see

Item11).Theyalsobreakapartmonolithicclassestoliberate

separablefunctionality,furtherreducingcoupling(seeItem33).

Theyimprovegenericity,becauseit'shardtowritetemplates

thatdon'tknowwhetherornotanoperationisamemberfora

giventype(seeItem67).

Usethisalgorithmtodeterminewhetherafunctionshouldbea

memberand/orfriend:

//Ifyouhavenochoicethenyouhavenochoice;makeit

amemberifitmustbe:

Ifthefunctionisoneoftheoperators=,->,[],or(),

whichmustbemembers:

Makeitamember.

//Ifitcanbeanonmembernonfriend,orbenefitsfrom

beinganonmemberfriend,doit:

Elseif:a)thefunctionneedsadifferenttypeasitslefthandargument(asdooperators>>or<<,forexample);

orb)itneedstypeconversionsonitsleftmostargument;

orc)itcanbeimplementedusingtheclass'spublic

interfacealone:

Makeitanonmember(andfriendifneededincases

a)andb)).

Ifitneedstobehavevirtually:



Addavirtualmemberfunctiontoprovidethe

virtualbehavior,andimplementthe

nonmemberintermsofthat.

Else:Makeitamember.



Examples

Example:basic_string.Thestandardbasic_stringisa

needlesslymonolithicclasswith103memberfunctionsofwhich

71couldbewrittenasnonmembernonfriendswithoutlossof

efficiency.Manyofthemduplicatefunctionalityalreadyavailable

asalgorithms,orarethemselvesalgorithmsthatwouldbe

usefulmorewidelyiftheyweren'tburiedinsidebasic_string.

(SeeItems5and32,and[Sutter04].)



References

[Lakos96]Đ3.6.1,Đ9.1.2[McConnell93]Đ5.1-4[Murray93]

Đ2.6[Meyers00][Stroustrup00]Đ10.3.2,Đ11.3.2,Đ11.3.5,

Đ11.5.2,Đ21.2.3.1[Sutter00]Đ20[Sutter04]Đ37-40



45.Alwaysprovidenewanddeletetogether

Summary

Discussion

Exceptions

References



Summary

They'reapackagedeal:Everyclass-specificoverloadvoid*

operatornew(parms)mustbeaccompaniedbya

correspondingoverloadvoidoperatordelete(void*,

parms),whereparmsisalistofextraparametertypes(of

whichthefirstisalwaysstd::size_t).Thesamegoesforthe

arrayformsnew[]anddelete[].



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

Chapter 44.  Prefer writing nonmember nonfriend functions

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

×