Tải bản đầy đủ - 0 (trang)
Chapter 89.  Write function objects correctly

Chapter 89.  Write function objects correctly

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

Summary

Becheap,beadaptable:Designfunctionobjectstobevalues

thatarecheaptocopy.Wherepossible,makethemadaptable

byinheritingfromunary_-orbinary_function.



Discussion

Functionobjectsaremodeledonfunctionpointers.Likefunction

pointers,theconventionistopassthembyvalue.Allofthe

standardalgorithmspassobjectsbyvalue,andyouralgorithms

shouldtoo.Forexample:

template

Functionfor_each(InputIterfirst,InputIterlast,Functionf



Therefore,functionobjectsmustbecheaptocopyand

monomorphic(immunetoslicing,soavoidvirtualfunctions;see

Item54).Butlargeand/orpolymorphicobjectsareuseful,and

usingthemisokay;justhidethesizeandrichnessusingthe

Pimplidiom(seeItem43),whichleavestheouterclassasthe

requiredcheap-to-copymonomorphictypethatstillaccesses

richstate.Theouterclassshould:

Beadaptable:Inheritfromunary_functionor

binary_function.(Seebelow.)

HaveaPimpl:Storeapointer(e.g.,shared_ptr)toa

large/richimplementation.

Havethefunctioncalloperator(s):Passthesethroughto

theimplementationobject.

Thatshouldbeallthat'sneededintheouterclass,otherthan

possiblyprovidingnon-defaultversionsofconstruction,

assignment,and/ordestruction.

Functionobjectsshouldbeadaptable.Thestandardbindersand



adaptersrelyoncertaintypedefs,whichareprovidedmost

convenientlywhenyourfunctionobjectderivesfrom

unary_functionorbinary_function.Instantiate

unary_functionorbinary_functionwiththesametypesas

youroperator()takesandreturns,exceptthatforeachnonpointertypestripoffanytop-levelconstsand&sfromthetype.

Avoidprovidingmultipleoperator()functions,becausethat

makesadaptabilitydifficult.It'susuallyimpossibletoprovide

therightadaptabilitytypedefsbecausethesametypedefwould

havedifferentvaluesfordifferentoperator()functions.

Notallfunctionobjectsarepredicates.Predicatesareasubset

offunctionobjects.(SeeItem87.)



References

[Allison98]Đ15,ĐC[Austern99]Đ4,Đ8,Đ15[Gamma95]

Bridge[Josuttis99]Đ8.2.4[Koenig97]Đ21,Đ29

[Meyers97]Đ34[Meyers01]Đ38,Đ40,Đ46[Musser01]Đ2.4,

Đ8,Đ23[Sutter00]Đ26-30[Vandevoorde03]Đ22



TypeSafety

Tryingtooutsmartacompilerdefeatsmuchofthe

purposeofusingone.

BrianKernighan&P.J.Plauger

Ifyoulietothecompiler,itwillgetitsrevenge.

HenrySpencer

Therewillalwaysbethingswewishtosayinour

programsthatinallknownlanguagescanonlybe

saidpoorly.

AlanPerlis

Last,butcertainlynotleast,wewillconsidertype

correctnessaveryimportantpropertyofaprogramthat

youshouldstrivetopreserveatalltimes.Theoretically,a

type-correctfunctioncanneveraccessuntypedmemory

orreturnforgedvalues.Practically,ifyourcodemaintains

typesoundness,itavoidsalargecategoryofnastyerrors

rangingfromnonportabilitytocorruptingmemoryto

creatingbogusvaluestoexhibitingundefinedbehavior.

Thebasicideaunderpinninghowtomaintaintype

soundnessistoalwaysreadbitsintheformatinwhich

theywerewritten.Sometimes,C++makesiteasyto

breakthisrule,andthefollowingItemsdetailhowto

avoidsuchmistakes.

OurvoteforthemostvaluableIteminthissectiongoesto

Item91:Relyontypes,notonrepresentations.Thetype

systemisyourfriendandyourstaunchestally;enlistits

help,andtrynevertoabuseitstrust.



90.Avoidtypeswitching;prefer

polymorphism

Summary

Discussion

Examples

References



Summary

Switchoff:Avoidswitchingonthetypeofanobjectto

customizebehavior.Usetemplatesandvirtualfunctionstolet

types(nottheircallingcode)decidetheirbehavior.



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

Chapter 89.  Write function objects correctly

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

×