Google C++Style Guidegoogle c++ 代码规范.docx
《Google C++Style Guidegoogle c++ 代码规范.docx》由会员分享,可在线阅读,更多相关《Google C++Style Guidegoogle c++ 代码规范.docx(57页珍藏版)》请在冰豆网上搜索。
GoogleC++StyleGuidegooglec++代码规范
GoogleC++StyleGuide
Revision3.188
BenjyWeinbergerCraigSilversteinGregoryEitzmannMarkMentovaiTashanaLandray
Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:
▽.Youmaytoggleallsummarieswiththebigarrowbutton:
▽Toggleallsummaries
HeaderFiles
The#defineGuardHeaderFileDependenciesInlineFunctionsThe-inl.hFilesFunctionParameterOrderingNamesandOrderofIncludes
Scoping
NamespacesNestedClassesNonmember,StaticMember,andGlobalFunctionsLocalVariablesStaticandGlobalVariables
Classes
DoingWorkinConstructorsDefaultConstructorsExplicitConstructorsCopyConstructorsStructsvs.ClassesInheritanceMultipleInheritanceInterfacesOperatorOverloadingAccessControlDeclarationOrderWriteShortFunctions
Google-SpecificMagic
SmartPointerscpplint
OtherC++Features
ReferenceArgumentsFunctionOverloadingDefaultArgumentsVariable-LengthArraysandalloca()FriendsExceptionsRun-TimeTypeInformation(RTTI)CastingStreamsPreincrementandPredecrementUseofconstIntegerTypes64-bitPortabilityPreprocessorMacros0andNULLsizeofBoostC++0x
Naming
GeneralNamingRulesFileNamesTypeNamesVariableNamesConstantNamesFunctionNamesNamespaceNamesEnumeratorNamesMacroNamesExceptionstoNamingRules
Comments
CommentStyleFileCommentsClassCommentsFunctionCommentsVariableCommentsImplementationCommentsPunctuation,SpellingandGrammarTODOCommentsDeprecationComments
Formatting
LineLengthNon-ASCIICharactersSpacesvs.TabsFunctionDeclarationsandDefinitionsFunctionCallsConditionalsLoopsandSwitchStatementsPointerandReferenceExpressionsBooleanExpressionsReturnValuesVariableandArrayInitializationPreprocessorDirectivesClassFormatConstructorInitializerListsNamespaceFormattingHorizontalWhitespaceVerticalWhitespace
ExceptionstotheRules
ExistingNon-conformantCodeWindowsCode
TableofContents
ImportantNote
DisplayingHiddenDetailsinthisGuide
link▽Thisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"Hooray"appearbelow.
Hooray!
Nowyouknowyoucanexpandpointstogetmoredetails.Alternatively,there'san"expandall"atthetopofthisdocument.
Background
C++isthemaindevelopmentlanguageusedbymanyofGoogle'sopen-sourceprojects.AseveryC++programmerknows,thelanguagehasmanypowerfulfeatures,butthispowerbringswithitcomplexity,whichinturncanmakecodemorebug-proneandhardertoreadandmaintain.
Thegoalofthisguideistomanagethiscomplexitybydescribingindetailthedosanddon'tsofwritingC++code.TheserulesexisttokeepthecodebasemanageablewhilestillallowingcoderstouseC++languagefeaturesproductively.
Style,alsoknownasreadability,iswhatwecalltheconventionsthatgovernourC++code.ThetermStyleisabitofamisnomer,sincetheseconventionscoverfarmorethanjustsourcefileformatting.
Onewayinwhichwekeepthecodebasemanageableisbyenforcingconsistency.Itisveryimportantthatanyprogrammerbeabletolookatanother'scodeandquicklyunderstandit.Maintainingauniformstyleandfollowingconventionsmeansthatwecanmoreeasilyuse"pattern-matching"toinferwhatvarioussymbolsareandwhatinvariantsaretrueaboutthem.Creatingcommon,requiredidiomsandpatternsmakescodemucheasiertounderstand.Insomecasestheremightbegoodargumentsforchangingcertainstylerules,butwenonethelesskeepthingsastheyareinordertopreserveconsistency.
AnotherissuethisguideaddressesisthatofC++featurebloat.C++isahugelanguagewithmanyadvancedfeatures.Insomecasesweconstrain,orevenban,useofcertainfeatures.Wedothistokeepcodesimpleandtoavoidthevariouscommonerrorsandproblemsthatthesefeaturescancause.Thisguideliststhesefeaturesandexplainswhytheiruseisrestricted.
Open-sourceprojectsdevelopedbyGoogleconformtotherequirementsinthisguide.
NotethatthisguideisnotaC++tutorial:
weassumethatthereaderisfamiliarwiththelanguage.
HeaderFiles
Ingeneral,every.ccfileshouldhaveanassociated.hfile.Therearesomecommonexceptions,suchasunittestsandsmall.ccfilescontainingjustamain()function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
link▽Allheaderfilesshouldhave#defineguardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe___H_.
Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'ssourcetree.Forexample,thefilefoo/src/bar/baz.hinprojectfooshouldhavethefollowingguard:
#ifndefFOO_BAR_BAZ_H_
#defineFOO_BAR_BAZ_H_
...
#endif//FOO_BAR_BAZ_H_
HeaderFileDependencies
link▽Don'tusean#includewhenaforwarddeclarationwouldsuffice.
Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.
Youcansignificantlyreducethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusestheFileclassinwaysthatdonotrequireaccesstothedeclarationoftheFileclass,yourheaderfilecanjustforwarddeclareclassFile;insteadofhavingto#include"file/base/file.h".
HowcanweuseaclassFooinaheaderfilewithoutaccesstoitsdefinition?
∙WecandeclaredatamembersoftypeFoo*orFoo&.
∙Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftypeFoo.(OneexceptionisifanargumentFooorconstFoo&hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)
∙WecandeclarestaticdatamembersoftypeFoo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.
Ontheotherhand,youmustincludetheheaderfileforFooifyourclasssubclassesFooorhasadatamemberoftypeFoo.
Sometimesitmakessensetohavepointer(orbetter,scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.
Ofcourse,.ccfilestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.
Note:
IfyouuseasymbolFooinyoursourcefile,youshouldbringinadefinitionforFooyourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.OneexceptionisifFooisusedinmyfile.cc,it'sokto#include(orforward-declare)Fooinmyfile.h,insteadofmyfile.cc.
InlineFunctions
link▽Definefunctionsinlineonlywhentheyaresmall,say,10linesorless.
Definition:
Youcandeclarefunctionsinawaythatallowsthecompilertoexpandtheminlineratherthancallingthemthroughtheusualfunctioncallmechanism.
Pros:
Inliningafunctioncangeneratemoreefficientobjectcode,aslongastheinlinedfunctionissmall.Feelfreetoinlineaccessorsandmutators,andothershort,performance-criticalfunctions.
Cons:
Overuseofinliningcanactuallymakeprogramsslower.Dependingonafunction'ssize,inliningitcancausethecodesizetoincreaseordecrease.Inliningaverysmallaccessorfunctionwillusuallydecreasecodesizewhileinliningaverylargefunctioncandramaticallyincreasecodesize.Onmodernprocessorssmallercodeusuallyrunsfasterduetobetteruseoftheinstructioncache.
Decision:
Adecentruleofthumbistonotinlineafunctionifitismorethan10lineslong.Bewareofdestructors,whichareoftenlongerthantheyappearbecauseofimplicitmember-andbase-destructorcalls!
Anotherusefulruleofthumb:
it'stypicallynotcosteffectivetoinlinefunctionswithloopsorswitchstatements(unless,inthecommoncase,thelooporswitchstatementisneverexecuted).
Itisimportanttoknowthatfunctionsarenotalwaysinlinedeveniftheyaredeclaredassuch;forexample,virtualandrecursivefunctionsarenotnormallyinlined.Usuallyrecursivefunctionsshouldnotbeinline.Themainreasonformakingavirtualfunctioninlineistoplaceitsdefinitionintheclass,eitherforconvenienceortodocumentitsbehavior,e.g.,foraccessorsandmutators.
The-inl.hFiles
link▽Youmayusefilenameswitha-inl.hsuffixtodefinecomplexinlinefunctionswhenneeded.
Thedefinitionofaninlinefunctionneedstobeinaheaderfile,sothatthecompilerhasthedefinitionavailableforinliningatthecallsites.However,implementationcodeproperlybelongsin.ccfiles,andwedonotliketohavemuchactualcodein.hfilesunlessthereisareadabilityorperformanceadvantage.
Ifaninlinefunctiondefinitionisshort,withverylittle,ifany,logicinit,youshouldputthecodeinyour.hfile.Forexample,accessorsandmutatorsshouldcertainlybeinsideaclassdefinition.Morecomplexinlinefunctionsmayalsobeputina.hfilefortheconvenienceoftheimplementerandcallers,thoughifthismakesthe.hfiletoounwieldyyoucaninsteadputthatcodeinaseparate-inl.hfile.Thisseparatestheimplementationfromtheclassdefinition,whilestillallowingtheimplementationtobeincludedwherenecessary.
Anotheruseof-inl.hfilesisfordefinitionsoffunctiontemplates.Thiscanbeusedtokeepyourtemplated