C++CodingStandards:101Rules,Guidelines,
andBestPractices
ByHerbSutter,AndreiAlexandrescu
Publisher :AddisonWesleyProfessional
PubDate :October25,2004
ISBN :0-321-11358-6
Pages :240
Consistent,high-qualitycodingstandardsimprovesoftware
quality,reducetime-to-market,promoteteamwork,eliminate
timewastedoninconsequentialmatters,andsimplify
maintenance.Now,twooftheworld'smostrespectedC++
expertsdistilltherichcollectiveexperienceoftheglobalC++
communityintoasetofcodingstandardsthateverydeveloper
anddevelopmentteamcanunderstandanduseasabasisfor
theirowncodingstandards.
Tableof
•
Contents
• Index
TheauthorscovervirtuallyeveryfacetofC++programming:
designandcodingstyle,functions,operators,classdesign,
inheritance,construction/destruction,copying,assignment,
namespaces,modules,templates,genericity,exceptions,STL
containersandalgorithms,andmore.Eachstandardisdescribed
concisely,withpracticalexamples.Fromtypedefinitiontoerror
handling,thisbookpresentsC++bestpractices,includingsome
thathaveonlyrecentlybeenidentifiedandstandardizedtechniquesyoumaynotknowevenifyou'veusedC++foryears.
Alongtheway,you'llfindanswerstoquestionslike
What'sworthstandardizingandwhatisn't?
Whatarethebestwaystocodeforscalability?
Whataretheelementsofarationalerrorhandlingpolicy?
How(andwhy)doyouavoidunnecessaryinitialization,
cyclic,anddefinitionaldependencies?
When(andhow)shouldyouusestaticanddynamic
polymorphismtogether?
Howdoyoupractice"safe"overriding?
Whenshouldyouprovideano-failswap?
Whyandhowshouldyoupreventexceptionsfrom
propagatingacrossmoduleboundaries?
Whyshouldn'tyouwritenamespacedeclarationsor
directivesinaheaderfile?
WhyshouldyouuseSTLvectorandstringinsteadofarrays?
HowdoyouchoosetherightSTLsearchorsortalgorithm?
Whatrulesshouldyoufollowtoensuretype-safecode?
Whetheryou'reworkingaloneorwithothers,C++Coding
Standardswillhelpyouwritecleanercodeandwriteitfaster,
withfewerhasslesandlessfrustration.
C++CodingStandards:101Rules,Guidelines,
andBestPractices
ByHerbSutter,AndreiAlexandrescu
Publisher :AddisonWesleyProfessional
PubDate :October25,2004
Tableof
•
ISBN :0-321-11358-6
Contents
Pages :240
• Index
Copyright
TheC++In-DepthSeries
TitlesintheSeries
Preface
HowtoUseThisBook
CodingStandardsandYou
AboutThisBook
Acknowledgments
OrganizationalandPolicyIssues
Chapter0.Don'tsweatthesmallstuff.(Or:Knowwhatnottostandardize.)
Summary
Discussion
Examples
References
Chapter1.Compilecleanlyathighwarninglevels
Summary
Discussion
Examples
Exceptions
References
Chapter2.Useanautomatedbuildsystem
Summary
Discussion
References
Chapter3.Useaversioncontrolsystem
Summary
Discussion
Exceptions
References
Chapter4.Investincodereviews
Summary
Discussion
References
DesignStyle
Chapter5.Giveoneentityonecohesiveresponsibility
Summary
Discussion
Examples
References
Chapter6.Correctness,simplicity,andclaritycomefirst
Summary
Discussion
Examples
References
Chapter7.Knowwhenandhowtocodeforscalability
Summary
Discussion
References
Chapter8.Don'toptimizeprematurely
Summary
Discussion
Examples
Exceptions
References
Chapter9.Don'tpessimizeprematurely
Summary
Discussion
References
Chapter10.Minimizeglobalandshareddata
Summary
Discussion
Exceptions
References
Chapter11.Hideinformation
Summary
Discussion
Exceptions
References
Chapter12.Knowwhenandhowtocodeforconcurrency
Summary
Discussion
References
Chapter13.Ensureresourcesareownedbyobjects.UseexplicitRAIIand
smartpointers
Summary
Discussion
Exceptions
References
CodingStyle
Chapter14.Prefercompile-andlink-timeerrorstorun-timeerrors
Summary
Discussion
Examples
Exceptions
References
Chapter15.Useconstproactively
Summary
Discussion
Examples
References
Chapter16.Avoidmacros
Summary
Discussion
Examples
Exceptions
References
Chapter17.Avoidmagicnumbers
Summary
Discussion
Examples
References
Chapter18.Declarevariablesaslocallyaspossible
Summary
Discussion
Exceptions
References
Chapter19.Alwaysinitializevariables
Summary
Discussion
Examples
Exceptions
References
Chapter20.Avoidlongfunctions.Avoiddeepnesting
Summary
Discussion
Exceptions
References
Chapter21.Avoidinitializationdependenciesacrosscompilationunits
Summary
Discussion
References
Chapter22.Minimizedefinitionaldependencies.Avoidcyclicdependencies
Summary
Discussion
Exceptions
References
Chapter23.Makeheaderfilesself-sufficient
Summary
Discussion
Examples
References
Chapter24.Alwayswriteinternal#includeguards.Neverwriteexternal
#includeguards
Summary
Discussion
Exceptions
References
FunctionsandOperators
Chapter25.Takeparametersappropriatelybyvalue,(smart)pointer,or
reference
Summary
Discussion
References
Chapter26.Preservenaturalsemanticsforoverloadedoperators
Summary
Discussion
Exceptions
References
None27.Preferthecanonicalformsofarithmeticandassignmentoperators
Summary
Discussion
Examples
Exceptions
References
Chapter28.Preferthecanonicalformof++and--.Prefercallingtheprefix
forms
Summary
Discussion
Exceptions
References
Chapter29.Consideroverloadingtoavoidimplicittypeconversions
Summary
Discussion
References
Chapter30.Avoidoverloading&&,||,or,(comma)
Summary
Discussion
Examples
Exceptions
References
Chapter31.Don'twritecodethatdependsontheorderofevaluationof
functionarguments
Summary
Discussion
References
ClassDesignandInheritance
Chapter32.Beclearwhatkindofclassyou'rewriting
Summary
Discussion
References
Chapter33.Preferminimalclassestomonolithicclasses
Summary
Discussion
References
Chapter34.Prefercompositiontoinheritance
Summary
Discussion
Exceptions
References
Chapter35.Avoidinheritingfromclassesthatwerenotdesignedtobebase
classes
Summary
Discussion
Examples
References
Chapter36.Preferprovidingabstractinterfaces
Summary
Discussion
Examples
Exceptions
References
Chapter37.Publicinheritanceissubstitutability.Inherit,nottoreuse,buttobe
reused
Summary
Discussion
Exceptions
References
Chapter38.Practicesafeoverriding
Summary
Discussion
Examples
References
Chapter39.Considermakingvirtualfunctionsnonpublic,andpublicfunctions
nonvirtual
Summary
Discussion
Exceptions
References
Chapter40.Avoidprovidingimplicitconversions
Summary
Discussion
Examples
Exceptions
References
Chapter41.Makedatamembersprivate,exceptinbehaviorlessaggregates
(C-stylestructs)
Summary
Discussion
Examples
Exceptions
References
Chapter42.Don'tgiveawayyourinternals
Summary
Discussion
Exceptions
References
Chapter43.Pimpljudiciously
Summary
Discussion
Exceptions
References
Chapter44.Preferwritingnonmembernonfriendfunctions
Summary
Discussion
Examples
References
Chapter45.Alwaysprovidenewanddeletetogether
Summary
Discussion
Exceptions
References
Chapter46.Ifyouprovideanyclass-specificnew,provideallofthestandard
forms(plain,in-place,andnothrow)
Summary
Discussion
References
Construction,Destruction,andCopying
Chapter47.Defineandinitializemembervariablesinthesameorder
Summary
Discussion
References
Chapter48.Preferinitializationtoassignmentinconstructors
Summary
Discussion
Exceptions
References
Chapter49.Avoidcallingvirtualfunctionsinconstructorsanddestructors
Summary
Discussion
Examples
References
Chapter50.Makebaseclassdestructorspublicandvirtual,orprotectedand
nonvirtual
Summary
Discussion
Examples
Exceptions
References
Chapter51.Destructors,deallocation,andswapneverfail
Summary
Discussion
References
Chapter52.Copyanddestroyconsistently
Summary
Discussion
Exceptions
References
Chapter53.Explicitlyenableordisablecopying
Summary
Discussion
References
Chapter54.Avoidslicing.ConsiderCloneinsteadofcopyinginbaseclasses
Summary
Discussion
Exceptions
References
Chapter55.Preferthecanonicalformofassignment
Summary
Discussion
References
Chapter56.Wheneveritmakessense,provideano-failswap(andprovideit
correctly)
Summary
Discussion
Exceptions
References
NamespacesandModules
Chapter57.Keepatypeanditsnonmemberfunctioninterfaceinthesame
namespace
Summary
Discussion
Examples
References
Chapter58.Keeptypesandfunctionsinseparatenamespacesunlessthey're
specificallyintendedtoworktogether
Summary
Discussion
References
Chapter59.Don'twritenamespaceusingsinaheaderfileorbeforean
#include
Summary
Discussion
Exceptions
References
Chapter60.Avoidallocatinganddeallocatingmemoryindifferentmodules
Summary
Discussion
References
Chapter61.Don'tdefineentitieswithlinkageinaheaderfile
Summary
Discussion
Exceptions
References
Chapter62.Don'tallowexceptionstopropagateacrossmoduleboundaries
Summary
Discussion
References
Chapter63.Usesufficientlyportabletypesinamodule'sinterface
Summary
Discussion
Examples
References
TemplatesandGenericity
Chapter64.Blendstaticanddynamicpolymorphismjudiciously
Summary
Discussion
References
Chapter65.Customizeintentionallyandexplicitly
Summary
Discussion
References
Chapter66.Don'tspecializefunctiontemplates
Summary
Discussion
Examples
References
Chapter67.Don'twriteunintentionallynongenericcode
Summary
Discussion
Exceptions
References
ErrorHandlingandExceptions
Chapter68.Assertliberallytodocumentinternalassumptionsandinvariants
Summary
Discussion
Examples
References
Chapter69.Establisharationalerrorhandlingpolicy,andfollowitstrictly
Summary
Discussion
References
Chapter70.Distinguishbetweenerrorsandnon-errors
Summary
Discussion
Examples
References
Chapter71.Designandwriteerror-safecode
Summary
Discussion
Examples
References
Chapter72.Prefertouseexceptionstoreporterrors
Summary
Discussion
Examples
Exceptions
References
Chapter73.Throwbyvalue,catchbyreference
Summary
Discussion
Examples
References
Chapter74.Report,handle,andtranslateerrorsappropriately
Summary
Discussion
Exceptions
References
Chapter75.Avoidexceptionspecifications
Summary
Discussion
Exceptions
References
STL:Containers
Chapter76.Usevectorbydefault.Otherwise,chooseanappropriatecontainer
Summary
Discussion
Examples
References
Chapter77.Usevectorandstringinsteadofarrays
Summary
Discussion
References
Chapter78.Usevector(andstring::c_str)toexchangedatawithnon-C++APIs
Summary
Discussion
References
Chapter79.Storeonlyvaluesandsmartpointersincontainers
Summary
Discussion
Examples
References
Chapter80.Preferpush_backtootherwaysofexpandingasequence
Summary
Discussion
Exceptions
References
Chapter81.Preferrangeoperationstosingle-elementoperations
Summary
Discussion
Examples
References
Chapter82.Usetheacceptedidiomstoreallyshrinkcapacityandreallyerase
elements
Summary
Discussion
Exceptions
References
STL:Algorithms
Chapter83.UseacheckedSTLimplementation
Summary
Discussion
Examples
References
Chapter84.Preferalgorithmcallstohandwrittenloops
Summary
Discussion
Examples
Exceptions
References
Chapter85.UsetherightSTLsearchalgorithm
Summary
Discussion
References
Chapter86.UsetherightSTLsortalgorithm
Summary
Discussion
Examples
Exceptions
References
Chapter87.Makepredicatespurefunctions
Summary
Discussion
Examples
References
Chapter88.Preferfunctionobjectsoverfunctionsasalgorithmandcomparer
arguments
Summary
Discussion
References
Chapter89.Writefunctionobjectscorrectly
Summary
Discussion
References
TypeSafety
Chapter90.Avoidtypeswitching;preferpolymorphism
Summary
Discussion
Examples
References
Chapter91.Relyontypes,notonrepresentations
Summary
Discussion
References
Chapter92.Avoidusingreinterpret_cast
Summary
Discussion
Exceptions
References
Chapter93.Avoidusingstatic_castonpointers
Summary
Discussion
References
Chapter94.Avoidcastingawayconst
Summary
Discussion
Exceptions
References
Chapter95.Don'tuseC-stylecasts
Summary
Discussion
References
Chapter96.Don'tmemcpyormemcmpnon-PODs
Summary
Discussion
References
Chapter97.Don'tuseunionstoreinterpretrepresentation
Summary
Discussion
Exceptions
References
Chapter98.Don'tusevarargs(ellipsis)
Summary
Discussion
References
Chapter99.Don'tuseinvalidobjects.Don'tuseunsafefunctions
Summary
Discussion
References
Chapter100.Don'ttreatarrayspolymorphically
Summary
Discussion
References
Bibliography
SummaryofSummaries
OrganizationalandPolicyIssues
DesignStyle
CodingStyle
FunctionsandOperators
ClassDesignandInheritance
Construction,Destruction,andCopying
NamespacesandModules
TemplatesandGenericity
ErrorHandlingandExceptions
STL:Containers
STL:Algorithms
TypeSafety
Index
Copyright
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Publisher:JohnWait
EditorinChief:DonO'Hagan
AcquisitionsEditor:PeterGordon
EditorialAssistant:KimBoedigheimer
MarketingManager:ChandaLeary-Coutu
CoverDesigner:ChutiPrasertsith
ManagingEditor:JohnFuller
ProjectEditor:LaraWysong
CopyEditor:KelliBrooks
ManufacturingBuyer:CarolMelville
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419
ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales
VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData:
Sutter,Herb.
C++codingstandards:101rules,guidelines,andbestpractices/HerbSu
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-321-11358-6(pbk.:alk.paper)
C++(Computerprogramlanguage)I.Alexandrescu,Andrei.II.Title.
QA76.73.C153S852004
005.13'3dc22
2004022605
Copyright©2005PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
OneLakeStreet
UpperSaddleRiver,NJ07458
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.Firstprinting,October2004
Dedication
ForthemillionsofcurrentC++programmers.
TheC++In-DepthSeries
BjarneStroustrup,Editor
"Ihavemadethisletterlongerthanusual,becauseIlack
thetimetomakeitshort."
BLAISEPASCAL
TheadventoftheISO/ANSIC++standardmarkedthe
beginningofaneweraforC++programmers.Thestandard
offersmanynewfacilitiesandopportunities,buthowcana
real-worldprogrammerfindthetimetodiscoverthekey
nuggetsofwisdomwithinthismassofinformation?TheC++
In-DepthSeriesminimizeslearningtimeandconfusionby
givingprogrammersconcise,focusedguidestospecifictopics.
Eachbookinthisseriespresentsasingletopic,atatechnical
levelappropriatetothattopic.TheSeries'practicalapproachis
designedtoliftprofessionalstotheirnextlevelofprogramming
skills.Writtenbyexpertsinthefield,theseshort,in-depth
monographscanbereadandreferencedwithoutthedistraction
ofunrelatedmaterial.Thebooksarecross-referencedwithin
theSeries,andalsoreferenceTheC++ProgrammingLanguage
byBjarneStroustrup.
AsyoudevelopyourskillsinC++,itbecomesincreasingly
importanttoseparateessentialinformationfromhypeandglitz,
andtofindthein-depthcontentyouneedinordertogrow.The
C++In-DepthSeriesprovidesthetools,concepts,techniques,
andnewapproachestoC++thatwillgiveyouacriticaledge.
TitlesintheSeries
AcceleratedC++:PracticalProgrammingbyExample,Andrew
KoenigandBarbaraE.Moo
AppliedC++:PracticalTechniquesforBuildingBetterSoftware,
PhilipRomanikandAmyMuntz
TheBoostGraphLibrary:UserGuideandReferenceManual,
JeremyG.Siek,Lie-QuanLee,andAndrewLumsdaine
C++CodingStandards:101Rules,Guidelines,andBest
Practices,HerbSutterandAndreiAlexandrescu
C++In-DepthBoxSet,BjarneStroustrup,AndreiAlexandrescu,
AndrewKoenig,BarbaraE.Moo,StanleyB.Lippman,andHerb
Sutter
C++NetworkProgramming,Volume1:MasteringComplexity
withACEandPatterns,DouglasC.SchmidtandStephenD.
Huston
C++NetworkProgramming,Volume2:SystematicReusewith
ACEandFrameworks,DouglasC.SchmidtandStephenD.
Huston
C++TemplateMetaprogramming:Concepts,Tools,and
TechniquesfromBoostandBeyond,DavidAbrahamsand
AlekseyGurtovoy
EssentialC++,StanleyB.Lippman
ExceptionalC++:47EngineeringPuzzles,Programming
Problems,andSolutions,HerbSutter
ExceptionalC++Style:40NewEngineeringPuzzles,
ProgrammingProblems,andSolutions,HerbSutter
ModernC++Design:GenericProgrammingandDesignPatterns
Applied,AndreiAlexandrescu
MoreExceptionalC++:40NewEngineeringPuzzles,
ProgrammingProblems,andSolutions,HerbSutter
Formoreinformation,checkouttheserieswebsiteat
www.awprofessional.com/series/indepth/
Preface
Getintoarutearly:Dothesameprocessthesameway.
Accumulateidioms.Standardize.Theonlydifference(!)
betweenShakespeareandyouwasthesizeofhisidiom
listnotthesizeofhisvocabulary.
AlanPerlis[emphasisours]
Thebestthingaboutstandardsisthattherearesomany
tochoosefrom.
Variouslyattributed
Wewanttoprovidethisbookasabasisforyourteam'scoding
standardsfortwoprincipalreasons:
Acodingstandardshouldreflectthecommunity'sbest
tried-and-trueexperience:Itshouldcontainprovenidioms
basedonexperienceandsolidunderstandingofthe
language.Inparticular,acodingstandardshouldbebased
firmlyontheextensiveandrichsoftwaredevelopment
literature,bringingtogetherrules,guidelines,andbest
practicesthatwouldotherwisebeleftscatteredthroughout
manysources.
Natureabhorsavacuum:Ifyoudon'tconsciouslysetout
reasonablerules,usuallysomeoneelsewilltrytopushtheir
ownsetofpetrulesinstead.Acodingstandardmadethat
wayusuallyhasalloftheleastdesirablepropertiesofa
codingstandard;forexample,manysuchstandardstryto
enforceaminimalisticC-styleuseofC++.
Manybadcodingstandardshavebeensetbypeoplewhodon't
understandthelanguagewell,don'tunderstandsoftware
developmentwell,ortrytolegislatetoomuch.Abadcoding
standardquicklylosescredibilityandatbestevenitsvalid
guidelinesareliabletobeignoredbydisenchanted
programmerswhodislikeordisagreewithitspoorerguidelines.
That's"atbest"atworst,abadstandardmightactuallybe
enforced.