Tải bản đầy đủ - 0 (trang)
Chapter 75.  Avoid exception specifications

Chapter 75.  Avoid exception specifications

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

Summary

Takeexceptiontothesespecifications:Don'twriteexception

specificationsonyourfunctionsunlessyou'reforcedto

(becauseothercodeyoucan'tchangehasalreadyintroduced

them;seeExceptions.)



Discussion

Inbrief,don'tbotherwithexceptionspecifications.Evenexperts

don'tbother.Themainproblemswithexceptionspecifications

arethatthey'reonly"sortof"partofthetypesystem,they

don'tdowhatmostpeoplethink,andyoualmostalwaysdon't

wantwhattheyactuallydo.

Exceptionspecificationsaren'tpartofafunction'stype,except

whentheyare.Theyformashadowtypesystemwhereby

writinganexceptionspecificationisvariously:

Illegal:Inatypedefforapointertofunction.

Allowed:Intheidenticalcodewithoutthetypedef.

Required:Inthedeclarationofavirtualfunctionthat

overridesabaseclassvirtualfunctionthathasanexception

specification.

Implicitandautomatic:Inthedeclarationofthe

constructors,assignmentoperators,anddestructorswhen

theyareimplicitlygeneratedbythecompiler.

Acommonbutneverthelessincorrectbeliefisthatexception

specificationsstaticallyguaranteethatfunctionswillthrowonly

listedexceptions(possiblynone),andenablecompiler

optimizationsbasedonthatknowledge.

Infact,exceptionspecificationsactuallydosomethingslightly

butfundamentallydifferent:Theycausethecompilertoinject

additionalrun-timeoverheadintheformofimplicittry/catch

blocksaroundthefunctionbodytoenforceviarun-time

checkingthatthefunctiondoesinfactemitonlylisted



exceptions(possiblynone),unlessthecompilercanstatically

provethattheexceptionspecificationcanneverbeviolatedin

whichcaseitisfreetooptimizethecheckingaway.And

exceptionspecificationscanbothenableandpreventfurther

compileroptimizations(besidestheinherentoverheadalready

described);forexample,somecompilersrefusetoinline

functionsthathaveexceptionspecifications.

Worstofall,however,isthatexceptionspecificationsareablunt

instrument:Whenviolated,bydefaulttheyimmediately

terminateyourprogram.Youcanregisteran

unexpected_handler,butit'shighlyunlikelytohelpyoumuch

becauseyougetexactlyoneglobalhandlerandtheonlyway

thehandlercouldavoidimmediatelycallingterminatewouldbe

torethrowanexceptionthatispermissiblebutbecauseyou

haveonlyonehandlerforyourwholeapplication,it'shardto

seehowitcoulddousefulrecoveryorusefullyknowwhat

exceptionsmightbelegalwithouttrivializingexception

specificationsaltogether(e.g.,followingthedisciplineofhaving

allexceptionspecificationsallowsomegeneral

UnknownExceptioneliminatesanyadvantagethathavingan

exceptionspecificationmighthavehadinthefirstplace).

Yougenerallycan'twriteusefulexceptionspecificationsfor

functiontemplatesanyway,becauseyougenerallycan'ttell

whatexceptionsthetypestheyoperateonmightthrow.

Payingaperformanceoverheadinexchangeforenforcements

thatarenearlyalwaysuselessbecausetheyarefatalifthey

everfireisanexcellentexampleofaprematurepessimization

(seeItem9).

TheseisnoeasyfixfortheproblemsdescribedinthisItem.In

particular,theproblemsarenoteasilysolvedbyswitchingto

staticchecking.Peopleoftensuggestswitchingfrom

dynamicallycheckedexceptionspecificationstostatically

checkedones,asprovidedinJavaandotherlanguages.In

short,thatjusttradesonesetofproblemsforanother;usersof



languageswithstaticallycheckedexceptionspecificationsseem

toequallyoftensuggestswitchingtodynamicallycheckedones.



Exceptions

Ifyouhavetooverrideabaseclassvirtualfunctionthatalready

hasanexceptionspecification(e.g.,ahem,

std::exception::what),andyoudon'thavetheabilityto

changetheclasstoremovetheexceptionspecifications(orto

convincetheclass'smaintainertoremovethem),youwillhave

towriteacompatibleexceptionspecificationonyouroverriding

function,andyoushouldprefertomakeitnolessrestrictive

thanthebaseversionsoastominimizethefrequencywith

whichitmightbeviolated:



classBase{////inaclasswrittenbys

virtualf()throw(X,Y,Z);//theauthorusedanexce

};//andifyoucan'tgethi



classMyDerived:publicBase{////theninyourownclass

virtualf()throw(X,Y,Z);//musthaveacompatible

};//theidentical)exceptio



[BoostLRG]'sexperienceisthatathrows-nothingexception

specification(i.e.,throw())onanon-inlinefunction"mayhave

somebenefitwithsomecompilers."Notastunning

endorsementfromoneofthemosthighlyregardedand

expertlydesignedC++libraryprojectsintheworld.



References

[BoostLRG][Stroustrup00]Đ14.1,Đ14.6[Sutter04]Đ13



STL:Containers

Bydefault,usevectorwhenyouneedacontainer.

BjarneStroustrup,[Stroustrup00]Đ17.7

Weknowthatyoualreadyprefertousestandard

containersinsteadofhandcraftedones.Butwhich

containershouldyouuse?Whatshould(andshouldn't)

youstoreincontainers,andwhy?Howshouldyou

populatethem?Whataretheessentialidiomstoknow?

Thissectioncoverstheanswerstothesequestionsand

more.Andit'snoaccidentthatthefirstthreeItemsofthe

sectionallbeginwiththewords:"Usevector".

OurvoteforthemostvaluableIteminthissectiongoesto

Item79:Storeonlyvaluesandsmartpointersin

containers.Tothisweadd:Ifyouuse[Boost]and

[C++TR104]fornothingelse,usethemforshared_ptr.



76.Usevectorbydefault.Otherwise,

chooseanappropriatecontainer

Summary

Discussion

Examples

References



Summary

Usingthe"rightcontainer"isgreat:Ifyouhaveagoodreason

touseaspecificcontainertype,usethatcontainertype

knowingthatyoudidtherightthing.

Soisusingvector:Otherwise,writevectorandkeepgoing

withoutbreakingstride,alsoknowingyoudidtherightthing.



Discussion

Herearethreefundamentalissuesandrelatedquestionsfor

programmingingeneral,andforchoosingacontainerin

particular:

Writeforcorrectness,simplicity,andclarityfirst(seeItem

6):Prefertochoosethecontainerthatwillletyouwritethe

clearestcode.Examples:Ifyouneedtoinsertataspecific

position,useasequencecontainer(e.g.,vector,list).If

youneedrandom-accessiterators,usevector,deque,or

string.Ifyouneeddictionary-likelookupslikec[0]=

42;,useanassociativecontainer(e.g.,set,map)butifyou

needanorderedassociativecollection,youcan'tusehashbased(nonstandardhash_orstandardunordered_)

containers.

Writeforefficiencyonlywhenandwherenecessary(see

Item8):Iflookupspeedisaprovencriticalconsideration,

basedonactualperformancedata,preferahash-based

(nonstandardhash_orstandardunordered_)containers,

thenasortedvector,thenasetormap,usuallyinthat

order.Eventhen,big-Ohdifferences(e.g.,linear-timevs.

logarithmic-time;seeItem7)onlymatterifthecontainers

arebigenoughtoswamptheconstantfactor,whichfor

containersofsmallobjectslikedoublesfrequentlydoesn't

happenuntilaftercontainersizesexceedseveralthousand

elements.

Prefertowritetransactional,stronglyerror-safecodewhere

reasonablypossible(seeItem71),anddon'tuseinvalid

objects(seeItem99):Ifyouneedtransactionalsemantics

forinsertinganderasingelements,orneedtominimize

iteratorinvalidations,preferanode-basedcontainer(e.g.,



list,set,map).

Otherwise,followtheStandard'sadvice:"vectoristhetypeof

sequencethatshouldbeusedbydefault."([C++03]Đ23.1.1)

Ifyoudoubtthisadvice,askyourselfifyoureallyhavea

compellingreasonnottousetheonlystandardcontainerthat

guaranteesallofthefollowingproperties.vectoraloneis:

Guaranteedtohavethelowestspaceoverheadofany

container(zerobytesperobject).

Guaranteedtohavethefastestaccessspeedtocontained

elementsofanycontainer.

Guaranteedtohaveinherentlocalityofreference,meaning

thatobjectsneareachotherinthecontainerare

guaranteedtobeneareachotherinmemory,whichisnot

guaranteedbyanyotherstandardcontainer.

Guaranteedtobelayout-compatiblewithC,unlikeany

otherstandardcontainer.(SeeItems77andChapter78)

Guaranteedtohavethemostflexibleiterators(random

accessiterators)ofanycontainer.

Almostcertaintohavethefastestiterators(pointers,or

classeswithcomparableperformancethatoftencompile

awaytothesamespeedaspointerswhennotindebug

mode),fasterthanthoseofallothercontainers.

Doyouhaveareasonnottousethatcontainerbydefault?If

youdohaveareason,becauseofyouranswerstothefirst

threequestioninthisItem,that'sjustgreatandperfectly

fineusetheothercontainerknowingyoudidtherightthing.If



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

Chapter 75.  Avoid exception specifications

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

×