google C++编程规范.docx
《google C++编程规范.docx》由会员分享,可在线阅读,更多相关《google C++编程规范.docx(78页珍藏版)》请在冰豆网上搜索。
googleC++编程规范
GoogleC++StyleGuide
Revision3.180
BenjyWeinberger
CraigSilverstein
GregoryEitzmann
MarkMentovai
TashanaLandray
Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:
▽.Youmaytoggleallsummarieswiththebigarrowbutton:
▽ Toggleallsummaries
TableofContents
HeaderFiles
The#defineGuard HeaderFileDependenciesInlineFunctions The-inl.hFilesFunctionParameterOrderingNamesandOrderofIncludes
Scoping
Namespaces NestedClassesNonmember,StaticMember,andGlobalFunctionsLocalVariables StaticandGlobalVariables
Classes
DoingWorkinConstructorsDefaultConstructors ExplicitConstructorsCopyConstructors Structsvs.ClassesInheritance MultipleInheritanceInterfaces OperatorOverloadingAccessControl DeclarationOrderWriteShortFunctions
Google-SpecificMagic
SmartPointers cpplint
OtherC++Features
ReferenceArguments FunctionOverloadingDefaultArgumentsVariable-LengthArraysandalloca() FriendsExceptions Run-TimeTypeInformation(RTTI)Casting StreamsPreincrementandPredecrement UseofconstIntegerTypes 64-bitPortabilityPreprocessorMacros 0andNULL sizeofBoost C++0x
Naming
GeneralNamingRules FileNames TypeNamesVariableNames ConstantNamesFunctionNames NamespaceNamesEnumeratorNames MacroNamesExceptionstoNamingRules
Comments
CommentStyle FileComments ClassCommentsFunctionComments VariableCommentsImplementationCommentsPunctuation,SpellingandGrammarTODOComments DeprecationComments
Formatting
LineLength Non-ASCIICharactersSpacesvs.TabsFunctionDeclarationsandDefinitionsFunctionCalls ConditionalsLoopsandSwitchStatementsPointerandReferenceExpressionsBooleanExpressions ReturnValuesVariableandArrayInitializationPreprocessorDirectives ClassFormatConstructorInitializerListsNamespaceFormatting HorizontalWhitespaceVerticalWhitespace
ExceptionstotheRules
ExistingNon-conformantCode WindowsCode
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 .cc fileshouldhaveanassociated .h file.Therearesomecommonexceptions,suchasunittestsandsmall .ccfilescontainingjusta main() function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
link▽
Allheaderfilesshouldhave #define guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe___H_.
Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'ssourcetree.Forexample,thefile foo/src/bar/baz.hinproject foo shouldhavethefollowingguard:
#ifndefFOO_BAR_BAZ_H_
#defineFOO_BAR_BAZ_H_
...
#endif//FOO_BAR_BAZ_H_
HeaderFileDependencies
link▽
Don'tusean #include whenaforwarddeclarationwouldsuffice.
Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.
Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusesthe Fileclassinwaysthatdonotrequireaccesstothedeclarationofthe File class,yourheaderfilecanjustforwarddeclare classFile; insteadofhavingto #include"file/base/file.h".
Howcanweuseaclass Foo inaheaderfilewithoutaccesstoitsdefinition?
∙Wecandeclaredatamembersoftype Foo* or Foo&.
∙Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftype Foo.(Oneexceptionisifanargument Foo or constFoo& hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)
∙Wecandeclarestaticdatamembersoftype Foo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.
Ontheotherhand,youmustincludetheheaderfilefor Foo ifyourclasssubclasses Foo orhasadatamemberoftype Foo.
Sometimesitmakessensetohavepointer(orbetter, scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.
Ofcourse, .cc filestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.
Note:
Ifyouuseasymbol Foo inyoursourcefile,youshouldbringinadefinitionfor Foo yourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.Oneexceptionisif Foo isusedin myfile.cc,it'sokto#include(orforward-declare) Foo in myfile.h,insteadof myfile.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.h suffixtodefinecomplexinlinefunctionswhenneeded.
Thedefinitionofaninlinefunctionneedstobeinaheaderfile,sothatthecompilerhasthedefinitionavailableforinliningatthecallsites.However,implementationcodeproperlybelongsin .cc files,andwedonotliketohavemuchactualcodein .h filesunlessthereisareadabilityorperformanceadvantage.
Ifaninlinefunctiondefinitionisshort,withverylittle,ifany,logicinit,youshouldputthecodeinyour .h file.Forexample,accessorsandmutatorsshouldcertainlybeinsideaclassdefinition.Morecomplexinlinefunctionsmayalsobeputina .h filefortheconvenienceoftheimplementerandcallers,thoughifthismakesthe .h filetoounwieldyyoucaninsteadputthatcodeinaseparate -inl.h file.Thisseparatestheimplementationfromtheclassdefinition,w