Tải bản đầy đủ (.pdf) (620 trang)

Addison wesley effective c++ third edition 55 specific ways to improve your programs and designs

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.63 MB, 620 trang )

EffectiveC++ThirdEdition55Specific
WaystoImproveYourProgramsand
Designs
ByScottMeyers
...............................................
Publisher:AddisonWesleyProfessional
PubDate:May12,2005
PrintISBN:0-321-33487-6
Pages:320

TableofContents|Index

ThefirsttwoeditionsofEffectiveC++wereembracedbyhundredsofthousandsof
programmersworldwide.Thereasonisclear:ScottMeyers'practicalapproachtoC++
describestherulesofthumbusedbytheexpertsthethingstheyalmostalwaysdooralmost
alwaysavoiddoingtoproduceclear,correct,efficientcode.Thebookisorganizedaround55
specificguidelines,eachofwhichdescribesawaytowritebetterC++.Eachisbackedby
concreteexamples.Forthisthirdedition,morethanhalfthecontentisnew,includingadded
chaptersonmanagingresourcesandusingtemplates.Topicsfromthesecondeditionhave
beenextensivelyrevisedtoreflectmoderndesignconsiderations,includingexceptions,design
patterns,andmultithreading.ImportantfeaturesofEffectiveC++include:Expertguidanceon
thedesignofeffectiveclasses,functions,templates,andinheritancehierarchies.Applications
ofnew"TR1"standardlibraryfunctionality,alongwithcomparisonstoexistingstandard
librarycomponents.InsightsintodifferencesbetweenC++andotherlanguages(e.g.,Java,
C#,C)thathelpdevelopersfromthoselanguagesassimilate"theC++way"ofdoingthings.


EffectiveC++ThirdEdition55Specific
WaystoImproveYourProgramsand
Designs
ByScottMeyers


...............................................
Publisher:AddisonWesleyProfessional
PubDate:May12,2005
PrintISBN:0-321-33487-6
Pages:320

TableofContents|Index



Copyright



PraiseforEffectiveC++,ThirdEdition



Addison-WesleyProfessionalComputingSeries



Preface



Acknowledgments




Introduction




Terminology
Chapter1.AccustomingYourselftoC++



Item1:ViewC++asafederationoflanguages



Item2:Preferconsts,enums,andinlinesto#defines



Item3:Useconstwheneverpossible



Item4:Makesurethatobjectsareinitializedbeforethey'reused



Chapter2.Constructors,Destructors,andAssignmentOperators




Item5:KnowwhatfunctionsC++silentlywritesandcalls



Item6:Explicitlydisallowtheuseofcompiler-generatedfunctionsyoudonotwant



Item7:Declaredestructorsvirtualinpolymorphicbaseclasses



Item8:Preventexceptionsfromleavingdestructors



Item9:Nevercallvirtualfunctionsduringconstructionordestruction



Item10:Haveassignmentoperatorsreturnareferenceto*this



Item11:Handleassignmenttoselfinoperator=



Item12:Copyallpartsofanobject




Chapter3.ResourceManagement



Item13:Useobjectstomanageresources.



Item14:Thinkcarefullyaboutcopyingbehaviorinresource-managingclasses.



Item15:Provideaccesstorawresourcesinresource-managingclasses.



Item16:Usethesameformincorrespondingusesofnewanddelete.



Item17:Storenewedobjectsinsmartpointersinstandalonestatements.




Chapter4.DesignsandDeclarations




Item18:Makeinterfaceseasytousecorrectlyandhardtouseincorrectly



Item19:Treatclassdesignastypedesign



Item20:Preferpass-by-reference-to-consttopass-by-value



Item21:Don'ttrytoreturnareferencewhenyoumustreturnanobject



Item22:Declaredatamembersprivate



Item23:Prefernon-membernon-friendfunctionstomemberfunctions









Item24:Declarenon-memberfunctionswhentypeconversionsshouldapplytoall
parameters
Item25:Considersupportforanon-throwingswap
Chapter5.Implementations



Item26:Postponevariabledefinitionsaslongaspossible.



Item27:Minimizecasting.



Item28:Avoidreturning"handles"toobjectinternals.



Item29:Striveforexception-safecode.



Item30:Understandtheinsandoutsofinlining.



Item31:Minimizecompilationdependenciesbetweenfiles.




Chapter6.InheritanceandObject-OrientedDesign



Item32:Makesurepublicinheritancemodels"is-a."



Item33:Avoidhidinginheritednames





Item34:Differentiatebetweeninheritanceofinterfaceandinheritanceof
implementation



Item35:Consideralternativestovirtualfunctions



Item36:Neverredefineaninheritednon-virtualfunction



Item37:Neverredefineafunction'sinheriteddefaultparametervalue




Item38:Model"has-a"or"is-implemented-in-terms-of"throughcomposition



Item39:Useprivateinheritancejudiciously




Item40:Usemultipleinheritancejudiciously
Chapter7.TemplatesandGenericProgramming



Item41:Understandimplicitinterfacesandcompile-timepolymorphism



Item42:Understandthetwomeaningsoftypename



Item43:Knowhowtoaccessnamesintemplatizedbaseclasses



Item44:Factorparameter-independentcodeoutoftemplates




Item45:Usememberfunctiontemplatestoaccept"allcompatibletypes."





Item46:Definenon-memberfunctionsinsidetemplateswhentypeconversionsare
desired



Item47:Usetraitsclassesforinformationabouttypes



Item48:Beawareoftemplatemetaprogramming



Chapter8.Customizingnewanddelete



Item49:Understandthebehaviorofthenew-handler



Item50:Understandwhenitmakessensetoreplacenewanddelete




Item51:Adheretoconventionwhenwritingnewanddelete



Item52:Writeplacementdeleteifyouwriteplacementnew




Chapter9.Miscellany
Item53:Payattentiontocompilerwarnings.





Item54:Familiarizeyourselfwiththestandardlibrary,includingTR1
Item.55:FamiliarizeyourselfwithBoost.



AppendixA.BeyondEffectiveC++



AppendixB.ItemMappingsBetweenSecondandThirdEditions




Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappearinthis
book,andthepublisherwasawareofatrademarkclaim,thedesignationshave
beenprintedwithinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,but
makenoexpressedorimpliedwarrantyofanykindandassumenoresponsibility
forerrorsoromissions.Noliabilityisassumedforincidentalorconsequential
damagesinconnectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantity
forbulkpurchasesorspecialsales,whichmayincludeelectronicversionsand/or
customcoversandcontentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales


ThisBookIsSafariEnabled

TheSafari®Enabledicononthecoverofyourfavoritetechnology
bookmeansthebookisavailablethroughSafariBookshelf.Whenyoubuythis

book,yougetfreeaccesstotheonlineeditionfor45days.
SafariBookshelfisanelectronicreferencelibrarythatletsyoueasilysearch


thousandsoftechnicalbooks,findcodesamples,downloadchapters,andaccess
technicalinformationwheneverandwhereveryouneedit.
Togain45-daySafariEnabledaccesstothisbook:
Goto />Completethebriefregistrationform
EnterthecouponcodeAAAA-AAAA-AAAA-AAAA-AAAA
IfyouhavedifficultyregisteringonSafariBookshelforaccessingtheonline
edition,pleasee-mail
VisitusontheWeb:www.awprofessional.com
LibraryofCongressControlNumber:2005010101
Copyright©2005PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationis
protectedbycopyright,andpermissionmustbeobtainedfromthepublisher
priortoanyprohibitedreproduction,storageinaretrievalsystem,or
transmissioninanyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregardingpermissions,
writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
OneLakeStreet
UpperSaddleRiver,NJ07458
TextprintedintheUnitedStatesonrecycledpaperatCourierinWestford,
Massachusetts.Firstprinting,May2005

Dedication
ForNancy,withoutwhomnothingwouldbemuchworthdoing



Wisdomandbeautyformaveryrarecombination.
PetroniusArbiterSatyricon,XCIV

Dedication
AndinmemoryofPersephone,19952004


PraiseforEffectiveC++,ThirdEdition
"ScottMeyers'book,EffectiveC++,ThirdEdition,isdistilled
programmingexperienceexperiencethatyouwouldotherwisehaveto
learnthehardway.ThisbookisagreatresourcethatIrecommendto
everybodywhowritesC++professionally."
PeterDulimov,ME,ngineer,RangesandAssessingUnit,NAVSYSCOM,
Australia
"Thethirdeditionisstillthebestbookonhowtoputallofthepiecesof
C++togetherinanefficient,cohesivemanner.IfyouclaimtobeaC++
programmer,youmustreadthisbook."
EricNagler,Consultant,Instructor,andauthorofLearningC++
"Thefirsteditionofthisbookranksamongthesmall(verysmall)number
ofbooksthatIcreditwithsignificantlyelevatingmyskillsasa
'professional'softwaredevel-oper.Liketheothers,itwaspracticalandeasy
toread,butloadedwithimportantadvice.EffectiveC++,ThirdEdition,
continuesthattradition.C++isaverypowerfulprogramminglanguage.If
Cgivesyouenoughropetohangyourself,C++isahard-warestorewith
lotsofhelpfulpeoplereadytotieknotsforyou.Masteringthepoints
discussedinthisbookwilldefinitelyincreaseyourabilitytoeffectivelyuse
C++andreduceyourstresslevel."
JackW.Reeves,ChiefExecutiveOfficer,BleadingEdgeSoftware
Technologies

"Everynewdeveloperjoiningmyteamhasoneassignmenttoreadthis
book."
MichaelLanzetta,SeniorSoftwareEngineer
"IreadthefirsteditionofEffectiveC++aboutnineyearsago,andit
immediatelybecamemyfavoritebookonC++.Inmyopinion,Effective


C++,ThirdEdition,remainsamust-readtodayforanyonewhowishesto
programeffectivelyinC++.WewouldliveinabetterworldifC++
programmershadtoreadthisbookbeforewritingtheirfirstlineof
professionalC++code."
DannyRabbani,SoftwareDevelopmentEngineer
"IencounteredthefirsteditionofScottMeyers'EffectiveC++asa
strugglingprogrammerinthetrenches,tryingtogetbetteratwhatIwas
doing.Whatalifesaver!IfoundMeyers'advicewaspractical,useful,and
effective,fulfillingthepromiseofthetitle100percent.Thethirdedition
bringsthepracticalrealitiesofusingC++inseriousdevelopmentprojects
rightuptodate,addingchaptersonthelanguage'sverylatestissuesand
features.Iwasdelightedtostillfindmyselflearningsomethinginteresting
andnewfromthelatesteditionofabookIalreadythoughtIknewwell."
MichaelTopic,TechnicalProgramManager
"FromScottMeyers,theguruofC++,thisisthedefinitiveguidefor
anyonewhowantstouseC++safelyandeffectively,oristransitioning
fromanyotherOOlanguagetoC++.Thisbookhasvaluableinformation
presentedinaclear,concise,entertaining,andinsightfulmanner."
SiddharthaKaranSingh,SoftwareDeveloper
"ThisshouldbethesecondbookonC++thatanydevelopershouldread,
afterageneralintroductorytext.ItgoesbeyondthehowandwhatofC++
toaddressthewhyandwherefore.Ithelpedmegofromknowingthe
syntaxtounderstandingthephilosophyofC++programming."

TimothyKnox,SoftwareDeveloper
"ThisisafantasticupdateofaclassicC++text.Meyerscoversalotofnew
groundinthisvolume,andeveryseriousC++programmershouldhavea
copyofthisnewedition."
JeffreySomers,GameProgrammer


"EffectiveC++,ThirdEdition,coversthethingsyoushouldbedoingwhen
writingcodeanddoesaterrificjobofexplainingwhythosethingsare
important.ThinkofitasbestpracticesforwritingC++."
JeffScherpelz,SoftwareDevelopmentEngineer
"AsC++embraceschange,ScottMeyers'EffectiveC++,ThirdEdition,
soarstoremaininperfectlock-stepwiththelanguage.Therearemanyfine
introductorybooksonC++,butexactlyonesecondbookstandsheadand
shouldersabovetherest,andyou'reholdingit.WithScottguidingtheway,
preparetodosomesoaringofyourown!"
LeorZolman,C++TrainerandPundit,BDSoftware
"Thisbookisamust-haveforbothC++veteransandnewbies.Afteryou
havefinishedreadingit,itwillnotcollectdustonyourbookshelfyouwill
refertoitallthetime."
SamLee,SoftwareDeveloper
"ReadingthisbooktransformsordinaryC++programmersintoexpertC++
programmers,step-by-step,using55easy-to-readitems,eachdescribing
onetechniqueortip."
JeffreyD.Oldham,Ph.D.,SoftwareEngineer,Google
"ScottMeyers'EffectiveC++bookshavelongbeenrequiredreadingfor
newandexperiencedC++programmersalike.Thisnewedition,
incorporatingalmostadecade'sworthofC++languagedevelopment,ishis
mostcontent-packedbookyet.Hedoesnotmerelydescribetheproblems
inherentinthelanguage,butinsteadheprovidesunambiguousandeasy-tofollowadviceonhowtoavoidthepitfallsandwrite'effectiveC++.'I

expecteveryC++programmertohavereadit."
PhilippK.Janert,Ph.D.,SoftwareDevelopmentManager
"EachpreviouseditionofEffectiveC++hasbeenthemust-havebookfor
developerswhohaveusedC++forafewmonthsorafewyears,long


enoughtostumbleintothetrapslatentinthisrichlanguage.Inthisthird
edition,ScottMeyersextensivelyrefresheshissoundadviceforthe
modernworldofnewlanguageandlibraryfeaturesandtheprogramming
stylesthathaveevolvedtousethem.Scott'sengagingwritingstylemakes
iteasytoassimilatehisguidelinesonyourwaytobecominganeffective
C++developer."
DavidSmallberg,Instructor,DevelopMentor;Lecturer,ComputerScience,
UCLA
"EffectiveC++hasbeencompletelyupdatedfortwenty-first-centuryC++
practiceandcancontinuetoclaimtobethefirstsecondbookforallC++
practitioners."
MatthewWilson,Ph.D.,authorofImperfectC++


Addison-WesleyProfessionalComputing
Series
BrianW.Kernighan,ConsultingEditor
MatthewH.Austern,GenericProgrammingandtheSTL:UsingandExtending
theC++StandardTemplateLibrary
DavidR.Butenhof,ProgrammingwithPOSIX®Threads
BrentCallaghan,NFSIllustrated
TomCargill,C++ProgrammingStyle
WilliamR.Cheswick/StevenM.Bellovin/AvielD.Rubin,FirewallsandInternet
Security,SecondEdition:RepellingtheWilyHacker

DavidA.Curry,UNIX®SystemSecurity:AGuideforUsersandSystem
Administrators
StephenC.Dewhurst,C++Gotchas:AvoidingCommonProblemsinCoding
andDesign
DanFarmer/WietseVenema,ForensicDiscovery
ErichGamma/RichardHelm/RalphJohnson/JohnVlissides,DesignPatterns:
ElementsofReusableObject-OrientedSoftware
ErichGamma/RichardHelm/RalphJohnsn/JohnVlissides,DesignPatternsCD:
ElementsofReusableObject-OrientedSoftware
PeterHaggar,PracticalJava™ProgrammingLanguageGuide
DavidR.Hanson,CInterfacesandImplementations:TechniquesforCreating
ReusableSoftware


MarkHarrison/MichaelMcLennan,EffectiveTcl/TkProgramming:Writing
BetterProgramswithTclandTk
MichiHenning/SteveVinoski,AdvancedCORBA®ProgrammingwithC++
BrianW.Kernighan/RobPike,ThePracticeofProgramming
S.Keshav,AnEngineeringApproachtoComputerNetworking:ATMNetworks,
theInternet,andtheTelephoneNetwork
JohnLakos,Large-ScaleC++SoftwareDesign
ScottMeyers,EffectiveC++CD:85SpecificWaystoImproveYourPrograms
andDesigns
ScottMeyers,EffectiveC++,ThirdEdition:55SpecificWaystoImproveYour
ProgramsandDesigns
ScottMeyers,MoreEffectiveC++:35NewWaystoImproveYourPrograms
andDesigns
ScottMeyers,EffectiveSTL:50SpecificWaystoImproveYourUseofthe
StandardTemplateLibrary
RobertB.Murray,C++StrategiesandTactics

DavidR.Musser/GillmerJ.Derge/AtulSaini,STLTutorialandReference
Guide,SecondEdition:C++ProgrammingwiththeStandardTemplateLibrary
JohnK.Ousterhout,TclandtheTkToolkit
CraigPartridge,GigabitNetworking
RadiaPerlman,Interconnections,SecondEdition:Bridges,Routers,Switches,
andInternetworkingProtocols
StephenA.Rago,UNIX®SystemVNetworkProgramming
EricS.Raymond,TheArtofUNIXProgramming


MarcJ.Rochkind,AdvancedUNIXProgramming,SecondEdition
CurtSchimmel,UNIX®SystemsforModernArchitectures:Symmetric
MultiprocessingandCachingforKernelProgrammers
W.RichardStevens,TCP/IPIllustrated,Volume1:TheProtocols
W.RichardStevens,TCP/IPIllustrated,Volume3:TCPforTransactions,HTTP,
NNTP,andtheUNIX®DomainProtocols
W.RichardStevens/BillFenner/AndrewM.Rudoff,UNIXNetwork
ProgrammingVolume1,ThirdEdition:TheSocketsNetworkingAPI
W.RichardStevens/StephenA.Rago,AdvancedProgrammingintheUNIX®
Environment,SecondEdition
W.RichardStevens/GaryR.Wright,TCP/IPIllustratedVolumes1-3BoxedSet
JohnViega/GaryMcGraw,BuildingSecureSoftware:HowtoAvoidSecurity
ProblemstheRightWay
GaryR.Wright/W.RichardStevens,TCP/IPIllustrated,Volume2:The
Implementation
RuixiYuan/W.TimothyStrayer,VirtualPrivateNetworks:Technologiesand
Solutions
Visitwww.awprofessional.com/series/professionalcomputingformore
informationaboutthesetitles.



Preface
IwrotetheoriginaleditionofEffectiveC++in1991.Whenthetimecamefora
secondeditionin1997,Iupdatedthematerialinimportantways,but,becauseI
didn'twanttoconfusereadersfamiliarwiththefirstedition,Ididmybestto
retaintheexistingstructure:48oftheoriginal50Itemtitlesremainedessentially
unchanged.Ifthebookwereahouse,thesecondeditionwastheequivalentof
fresheningthingsupbyreplacingcarpets,paint,andlightfixtures.
Forthethirdedition,Itoretheplacedowntothestuds.(ThereweretimesI
wishedI'dgoneallthewaytothefoundation.)TheworldofC++hasundergone
enormouschangesince1991,andthegoalofthisbooktoidentifythemost
importantC++programmingguidelinesinasmall,readablepackagewasno
longerservedbytheItemsI'destablishednearly15yearsearlier.In1991,itwas
reasonabletoassumethatC++programmerscamefromaCbackground.Now,
programmersmovingtoC++arejustaslikelytocomefromJavaorC#.In1991,
inheritanceandobject-orientedprogrammingwerenewtomostprogrammers.
Nowthey'rewell-establishedconcepts,andexceptions,templates,andgeneric
programmingaretheareaswherepeopleneedmoreguidance.In1991,nobody
hadheardofdesignpatterns.Nowit'shardtodiscusssoftwaresystemswithout
referringtothem.In1991,workhadjustbegunonaformalstandardforC++.
Nowthatstandardiseightyearsold,andworkhasbegunonthenextversion.
Toaddressthesechanges,IwipedtheslateascleanasIcouldandaskedmyself,
"WhatarethemostimportantpiecesofadviceforpracticingC++programmers
in2005?"TheresultisthesetofItemsinthisnewedition.Thebookhasnew
chaptersonresourcemanagementandonprogrammingwithtemplates.Infact,
templateconcernsarewoventhroughoutthetext,becausetheyaffectalmost
everythinginC++.Thebookalsoincludesnewmaterialonprogramminginthe
presenceofexceptions,onapplyingdesignpatterns,andonusingthenewTR1
libraryfacilities.(TR1isdescribedinItem54.)Itacknowledgesthattechniques
andapproachesthatworkwellinsingle-threadedsystemsmaynotbe

appropriateinmultithreadedsystems.Welloverhalfthematerialinthebookis
new.However,mostofthefundamentalinformationinthesecondedition
continuestobeimportant,soIfoundawaytoretainitinoneformoranother.


(You'llfindamappingbetweenthesecondandthirdeditionItemsinAppendix
B.)
I'veworkedhardtomakethisbookasgoodasIcan,butIhavenoillusionsthat
it'sperfect.IfyoufeelthatsomeoftheItemsinthisbookareinappropriateas
generaladvice;thatthereisabetterwaytoaccomplishataskexaminedinthe
book;orthatoneormoreofthetechnicaldiscussionsisunclear,incomplete,or
misleading,pleasetellme.Ifyoufindanerrorofanykindtechnical,
grammatical,typographical,whateverpleasetellmethat,too.I'llgladlyaddto
theacknowledgmentsinlaterprintingsthenameofthefirstpersontobringeach
problemtomyattention.
EvenwiththenumberofItemsexpandedto55,thesetofguidelinesinthisbook
isfarfromexhaustive.Butcomingupwithgoodrulesonesthatapplytoalmost
allapplicationsalmostallthetimeisharderthanitmightseem.Ifyouhave
suggestionsforadditionalguidelines,Iwouldbedelightedtohearaboutthem.
Imaintainalistofchangestothisbooksinceitsfirstprinting,includingbug
fixes,clarifications,andtechnicalupdates.ThelistisavailableattheEffective
C++Erratawebpage,If
you'dliketobenotifiedwhenIupdatethelist,Iencourageyoutojoinmy
mailinglist.Iuseittomakeannouncementslikelytointerestpeoplewhofollow
myprofessionalwork.Fordetails,consult />SCOTTDOUGLASMEYERSSTAFFORD,OREGON
APRIL2005


Acknowledgments
EffectiveC++hasexistedforfifteenyears,andIstartedlearningC++aboutfive

yearsbeforeIwrotethebook.The"EffectiveC++project"hasthusbeenunder
developmentfortwodecades.Duringthattime,Ihavebenefitedfromthe
insights,suggestions,corrections,and,occasionally,dumbfoundedstaresof
hundreds(thousands?)ofpeople.EachhashelpedimproveEffectiveC++.Iam
gratefultothemall.
I'vegivenuptryingtokeeptrackofwhereIlearnedwhat,butonegeneralsource
ofinformationhashelpedmeaslongasIcanremember:theUsenetC++
newsgroups,especiallycomp.lang.c++.moderatedand
comp.std.c++.ManyoftheItemsinthisbookperhapsmosthavebenefited
fromthevettingoftechnicalideasatwhichtheparticipantsinthesenewsgroups
excel.
Regardingnewmaterialinthethirdedition,SteveDewhurstworkedwithmeto
comeupwithaninitialsetofcandidateItems.InItem11,theideaof
implementingoperator=viacopy-and-swapcamefromHerbSutter's
writingsonthetopic,e.g.,Item13ofhisExceptionalC++(Addison-Wesley,
2000).RAII(seeItem13)isfromBjarneStroustrup'sTheC++Programming
Language(Addison-Wesley,2000).TheideabehindItem17camefromthe
"BestPractices"sectionoftheBoostshared_ptrwebpage,
andwasrefinedby
Item21ofHerbSutter'sMoreExceptionalC++(Addison-Wesley,2002).Item
29wasstronglyinfluencedbyHerbSutter'sextensivewritingsonthetopic,e.g.,
Items8-19ofExceptionalC++,Items1723ofMoreExceptionalC++,and
Items1113ofExceptionalC++Style(Addison-Wesley,2005);DavidAbrahams
helpedmebetterunderstandthethreeexceptionsafetyguarantees.TheNVI
idiominItem35isfromHerbSutter'scolumn,"Virtuality,"intheSeptember
2001C/C++UsersJournal.InthatsameItem,theTemplateMethodand
StrategydesignpatternsarefromDesignPatterns(Addison-Wesley,1995)by
ErichGamma,RichardHelm,RalphJohnson,andJohnVlissides.Theideaof
usingtheNVIidiominItem37camefromHendrikSchober.DavidSmallberg
contributedthemotivationforwritingacustomsetimplementationinItem38.



Item39'sobservationthattheEBOgenerallyisn'tavailableundermultiple
inheritanceisfromDavidVandevoorde'sandNicolaiM.Josuttis'C++
Templates(Addison-Wesley,2003).InItem42,myinitialunderstandingabout
typenamecamefromGregComeau'sC++andCFAQ
(andLeorZolman
helpedmerealizethatmyunderstandingwasincorrect.(Myfault,notGreg's.)
TheessenceofItem46isfromDanSaks'talk,"MakingNewFriends."Theidea
attheendofItem52thatifyoudeclareoneversionofoperatornew,you
shoulddeclarethemall,isfromItem22ofHerbSutter'sExceptionalC++Style.
MyunderstandingoftheBoostreviewprocess(summarizedinItem55)was
refinedbyDavidAbrahams.
EverythingabovecorrespondstowhoorwhereIlearnedaboutsomething,not
necessarilytowhoorwherethethingwasinventedorfirstpublished.
MynotestellmethatIalsousedinformationfromSteveClamage,Antoine
Trux,TimothyKnox,andMikeKaelbling,though,regrettably,thenotesfailto
tellmehoworwhere.
DraftsofthefirsteditionwerereviewedbyTomCargill,GlennCarroll,Tony
Davis,BrianKernighan,JakKirman,DougLea,MoisesLejter,EugeneSantos,
Jr.,JohnShewchuk,JohnStasko,BjarneStroustrup,BarbaraTilly,andNancyL.
Urbano.IreceivedsuggestionsforimprovementsthatIwasabletoincorporate
inlaterprintingsfromNancyL.Urbano,ChrisTreichel,DavidCorbin,Paul
Gibson,SteveVinoski,TomCargill,NeilRhodes,DavidBern,RussWilliams,
RobertBrazile,DougMorgan,UweSteinmüller,MarkSomer,DougMoore,
DavidSmallberg,SethMeltzer,OlegShteynbuk,DavidPapurt,TonyHansen,
PeterMcCluskey,StefanKuhlins,DavidBraunegg,PaulChisholm,AdamZell,
ClovisTondo,MikeKaelbling,NatrajKini,LarsNyman,GregLutz,Tim
Johnson,JohnLakos,RogerScott,ScottFrohman,AlanRooks,RobertPoor,
EricNagler,AntoineTrux,CadeRoux,ChandrikaGokul,RandyMangoba,and

GlennTeitelbaum.
DraftsofthesecondeditionwerereviewedbyDerekBosch,TimJohnson,Brian
Kernighan,JunichiKimura,ScottLewandowski,LauraMichaels,David
Smallberg,ClovisTondo,ChrisVanWyk,andOlegZabluda.Laterprintings
benefitedfromcommentsfromDanielSteinberg,ArunprasadMarathe,Doug
Stapp,RobertHall,CherylFerguson,GaryBartlett,MichaelTamm,Kendall


Beaman,EricNagler,MaxHailperin,JoeGottman,RichardWeeks,Valentin
Bonnard,JunHe,TimKing,DonMaier,TedHill,MarkHarrison,Michael
Rubenstein,MarkRodgers,DavidGoh,BrentonCooper,AndyThomas-Cramer,
AntoineTrux,JohnWait,BrianSharon,LiamFitzpatrick,BerndMohr,Gary
Yee,JohnO'Hanley,BradyPatterson,ChristopherPeterson,FeliksKluzniak,Isi
Dunietz,ChristopherCreutzi,IanCooper,CarlHarris,MarkStickel,ClayBudin,
PanayotisMatsinopoulos,DavidSmallberg,HerbSutter,PajoMisljencevic,
GiulioAgostini,FredrikBlomqvist,JimmySnyder,ByrialJensen,Witold
Kuzminski,KazunobuKuriyama,MichaelChristensen,JorgeYáñezTeruel,
MarkDavis,MartyRabinowitz,AresLagae,andAlexanderMedvedev.
AnearlypartialdraftofthiseditionwasreviewedbyBrianKernighan,Angelika
Langer,JesseLaeuchli,RogerE.Pedersen,ChrisVanWyk,NicholasStroustrup,
andHendrikSchober.ReviewersforafulldraftwereLeorZolman,MikeTsao,
EricNagler,GeneGutnik,DavidAbrahams,GerhardKreuzer,Drosos
Kourounis,BrianKernighan,AndrewKirmse,BalogPal,EmilyJagdhar,Eugene
Kalenkovich,MikeRoze,EnricoCarrara,BenjaminBerck,JackReeves,Steve
Schirripa,MartinFallenstedt,TimothyKnox,YunBai,MichaelLanzetta,Philipp
Janert,GuidoBartolucci,MichaelTopic,JeffScherpelz,ChrisNauroth,Nishant
Mittal,JeffSomers,HalMoroff,VincentManis,BrandonChang,GregLi,Jim
Meehan,AlanGeller,SiddharthaSingh,SamLee,SasanDashtinezhad,Alex
Marin,SteveCai,ThomasFruchterman,CoryHicks,DavidSmallberg,
GunavardhanKakulapati,DannyRabbani,JakeCohen,HendrikSchober,Paco

Viciana,GlennKennedy,JeffreyD.Oldham,NicholasStroustrup,Matthew
Wilson,AndreiAlexandrescu,TimJohnson,LeonMatthews,PeterDulimov,
andKevlinHenney.DraftsofsomeindividualItemswerereviewedbyHerb
SutterandAttilaF.Feher.
Reviewinganunpolished(possiblyincomplete)manuscriptisdemandingwork,
anddoingitundertimepressureonlymakesitharder.Icontinuetobegrateful
thatsomanypeoplehavebeenwillingtoundertakeitforme.
Reviewingisharderstillifyouhavenobackgroundinthematerialbeing
discussedandareexpectedtocatcheveryprobleminthemanuscript.
Astonishingly,somepeoplestillchoosetobecopyeditors.Chrysta
Meadowbrookewasthecopyeditorforthisbook,andherverythoroughwork
exposedmanyproblemsthateludedeveryoneelse.


LeorZolmancheckedallthecodeexamplesagainstmultiplecompilersin
preparationforthefullreview,thendiditagainafterIrevisedthemanuscript.If
anyerrorsremain,I'mresponsibleforthem,notLeor.
KarlWiegersandespeciallyTimJohnsonofferedrapid,helpfulfeedbackon
backcovercopy.
JohnWait,myeditorforthefirsttwoeditionsofthisbook,foolishlysignedup
foranothertourofdutyinthatcapacity.Hisassistant,DeniseMickelsen,adroitly
handledmyfrequentpesteringwithapleasantsmile.(AtleastIthinkshe'sbeen
smiling.I'veneveractuallyseenher.)JulieNahildrewtheshortstrawandhence
becamemyproductionmanager.Shehandledtheovernightlossofsixweeksin
theproductionschedulewithremarkableequanimity.JohnFuller(herboss)and
MartyRabinowitz(hisboss)helpedoutwithproductionissues,too.Vanessa
Moore'sofficialjobwastohelpwithFrameMakerissuesandPDFpreparation,
butshealsoaddedtheentriestoAppendixBandformatteditforprintingonthe
insidecover.SolveigHauglandhelpedwithindexformatting.SandraSchroeder
andChutiPrasertsithwereresponsibleforcoverdesign,thoughChutiseemsto

havebeentheonewhohadtoreworkthecovereachtimeIsaid,"Butwhatabout
thisphotowithastripeofthatcolor...?"ChandaLeary-Coutugottappedforthe
heavyliftinginmarketing.
DuringthemonthsIworkedonthemanuscript,theTVseriesBuffytheVampire
Slayeroftenhelpedme"de-stress"attheendoftheday.Onlywithgreatrestraint
haveIkeptBuffyspeakoutofthebook.
KathyReedtaughtmeprogrammingin1971,andI'mgratifiedthatweremain
friendstothisday.DonaldFrenchhiredmeandMoisesLejtertocreateC++
trainingmaterialsin1989(anactthatledtomyreallyknowingC++),andin
1991heengagedmetopresentthematStratusComputer.Thestudentsinthat
classencouragedmetowritewhatultimatelybecamethefirsteditionofthis
book.DonalsointroducedmetoJohnWait,whoagreedtopublishit.
Mywife,NancyL.Urbano,continuestoencouragemywriting,evenafterseven
bookprojects,aCDadaptation,andadissertation.Shehasunbelievable
forbearance.Icouldn'tdowhatIdowithouther.
Fromstarttofinish,ourdog,Persephone,hasbeenacompanionwithoutequal.


Sadly,formuchofthisproject,hercompanionshiphastakentheformofanurn
intheoffice.Wereallymissher.


Introduction
Learningthefundamentalsofaprogramminglanguageisonething;learning
howtodesignandimplementeffectiveprogramsinthatlanguageissomething
elseentirely.ThisisespeciallytrueofC++,alanguageboastinganuncommon
rangeofpowerandexpressiveness.Properlyused,C++canbeajoytowork
with.Anenormousvarietyofdesignscanbedirectlyexpressedandefficiently
implemented.Ajudiciouslychosenandcarefullycraftedsetofclasses,
functions,andtemplatescanmakeapplicationprogrammingeasy,intuitive,

efficient,andnearlyerror-free.Itisn'tundulydifficulttowriteeffectiveC++
programs,ifyouknowhowtodoit.Usedwithoutdiscipline,however,C++can
leadtocodethatisincomprehensible,unmaintainable,inextensible,inefficient,
andjustplainwrong.
ThepurposeofthisbookistoshowyouhowtouseC++effectively.Iassume
youalreadyknowC++asalanguageandthatyouhavesomeexperienceinits
use.WhatIprovidehereisaguidetousingthelanguagesothatyoursoftwareis
comprehensible,maintainable,portable,extensible,efficient,andlikelyto
behaveasyouexpect.
TheadviceIprofferfallsintotwobroadcategories:generaldesignstrategies,
andthenutsandboltsofspecificlanguagefeatures.Thedesigndiscussions
concentrateonhowtochoosebetweendifferentapproachestoaccomplishing
somethinginC++.Howdoyouchoosebetweeninheritanceandtemplates?
Betweenpublicandprivateinheritance?Betweenprivateinheritanceand
composition?Betweenmemberandnon-memberfunctions?Betweenpass-byvalueandpass-by-reference?It'simportanttomakethesedecisionscorrectlyat
theoutset,becauseapoorchoicemaynotbecomeapparentuntilmuchlaterin
thedevelopmentprocess,atwhichpointrectifyingitisoftendifficult,timeconsuming,andexpensive.
Evenwhenyouknowexactlywhatyouwanttodo,gettingthingsjustrightcan
betricky.What'stheproperreturntypeforassignmentoperators?Whenshoulda
destructorbevirtual?Howshouldoperatornewbehavewhenitcan'tfind
enoughmemory?It'scrucialtosweatdetailslikethese,becausefailuretodoso


almostalwaysleadstounexpected,possiblymystifyingprogrambehavior.This
bookwillhelpyouavoidthat.
ThisisnotacomprehensivereferenceforC++.Rather,it'sacollectionof55
specificsuggestions(IcallthemItems)forhowyoucanimproveyourprograms
anddesigns.EachItemstandsmoreorlessonitsown,butmostalsocontain
referencestootherItems.Onewaytoreadthebook,then,istostartwithanItem
ofinterest,thenfollowitsreferencestoseewheretheyleadyou.

Thebookisn'tanintroductiontoC++,either.InChapter2,forexample,I'm
eagertotellyouallabouttheproperimplementationsofconstructors,
destructors,andassignmentoperators,butIassumeyoualreadyknoworcango
elsewheretofindoutwhatthesefunctionsdoandhowtheyaredeclared.A
numberofC++bookscontaininformationsuchasthat.
ThepurposeofthisbookistohighlightthoseaspectsofC++programmingthat
areoftenoverlooked.Otherbooksdescribethedifferentpartsofthelanguage.
Thisbooktellsyouhowtocombinethosepartssoyouendupwitheffective
programs.Otherbookstellyouhowtogetyourprogramstocompile.Thisbook
tellsyouhowtoavoidproblemsthatcompilerswon'ttellyouabout.
Atthesametime,thisbooklimitsitselftostandardC++.Onlyfeaturesinthe
officiallanguagestandardhavebeenusedhere.Portabilityisakeyconcernin
thisbook,soifyou'relookingforplatform-dependenthacksandkludges,thisis
nottheplacetofindthem.
Anotherthingyouwon'tfindinthisbookistheC++Gospel,theOneTruePath
toperfectC++software.EachoftheItemsinthisbookprovidesguidanceon
howtodevelopbetterdesigns,howtoavoidcommonproblems,orhowto
achievegreaterefficiency,butnoneoftheItemsisuniversallyapplicable.
Softwaredesignandimplementationisacomplextask,onecoloredbythe
constraintsofthehardware,theoperatingsystem,andtheapplication,sothebest
Icandoisprovideguidelinesforcreatingbetterprograms.
Ifyoufollowalltheguidelinesallthetime,youareunlikelytofallintothemost
commontrapssurroundingC++,butguidelines,bytheirnature,haveexceptions.
That'swhyeachItemhasanexplanation.Theexplanationsarethemost
importantpartofthebook.OnlybyunderstandingtherationalebehindanItem


canyoudeterminewhetheritappliestothesoftwareyouaredevelopingandto
theuniqueconstraintsunderwhichyoutoil.
ThebestuseofthisbookistogaininsightintohowC++behaves,whyit

behavesthatway,andhowtouseitsbehaviortoyouradvantage.Blind
applicationoftheItemsinthisbookisclearlyinappropriate,butatthesame
time,youprobablyshouldn'tviolateanyoftheguidelineswithoutagoodreason.


Terminology
ThereisasmallC++vocabularythateveryprogrammershouldunderstand.The
followingtermsareimportantenoughthatitisworthmakingsureweagreeon
whattheymean.
Adeclarationtellscompilersaboutthenameandtypeofsomething,butitomits
certaindetails.Thesearedeclarations:

externintx;//objectdeclar

std::size_tnumDigits(intnumber);//functiondecl

classWidget;//classdeclara

template<typenameT>//templatedecl

classGraphNode;//(seeItem42

//theuseof"t

NotethatIrefertotheintegerxasan"object,"eventhoughit'sofbuilt-intype.
Somepeoplereservethename"object"forvariablesofuser-definedtype,but
I'mnotoneofthem.AlsonotethatthefunctionnumDigits'returntypeis
std::size_t,i.e.,thetypesize_tinnamespacestd.Thatnamespaceis
wherevirtuallyeverythinginC++'sstandardlibraryislocated.However,



×