Googlec++编程规范Word下载.docx
《Googlec++编程规范Word下载.docx》由会员分享,可在线阅读,更多相关《Googlec++编程规范Word下载.docx(60页珍藏版)》请在冰豆网上搜索。
Nonmember,StaticMember,andGlobalFunctions
LocalVariables
StaticandGlobalVariables
Classes
DoingWorkinConstructors
DefaultConstructors
ExplicitConstructors
CopyConstructors
Structsvs.Classes
Inheritance
MultipleInheritance
Interfaces
OperatorOverloading
AccessControlDeclarationOrder
WriteShortFunctions
Google-SpecificMagic
SmartPointers
cpplint
OtherC++Features
ReferenceArguments
FunctionOverloading
DefaultArguments
Variable-LengthArraysandalloca()
Friends
Exceptions
Run-TimeTypeInformation(RTTI)
Casting
Streams
PreincrementandPredecrementUseofconst
IntegerTypes
64-bitPortability
PreprocessorMacros
0andNULL
sizeof
Boost
C++11
Naming
GeneralNamingRules
FileNames
TypeNames
VariableNames
ConstantNames
FunctionNames
NamespaceNames
EnumeratorNames
MacroNames
ExceptionstoNamingRules
Comments
CommentStyle
FileComments
ClassComments
FunctionComments
VariableComments
ImplementationComments
Punctuation,SpellingandGrammar
TODOComments
DeprecationComments
Formatting
LineLength
Non-ASCIICharacters
Spacesvs.Tabs
FunctionDeclarationsandDefinitions
FunctionCalls
Conditionals
LoopsandSwitchStatements
PointerandReferenceExpressions
BooleanExpressionsReturnValues
VariableandArrayInitialization
PreprocessorDirectives
ClassFormat
ConstructorInitializerLists
NamespaceFormatting
HorizontalWhitespace
VerticalWhitespace
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.
Onewayinwhichwekeepthecodebasemanageableisbyenforcing
consistency.Itisveryimportantthatanyprogrammerbeabletolookatanother'
scodeandquicklyunderstandit.Maintainingauniformstyleandfollowingconventionsmeansthatwecanmoreeasilyuse"
pattern-matching"
toinferwhatvarioussymbolsareandwhatinvariantsaretrueaboutthem.Creatingcommon,requiredidiomsandpatternsmakescodemucheasiertounderstand.Insomecasestheremightbegoodargumentsforchangingcertainstylerules,butwenonethelesskeepthingsastheyareinordertopreserveconsistency.
AnotherissuethisguideaddressesisthatofC++featurebloat.C++isahugelanguagewithmanyadvancedfeatures.Insomecasesweconstrain,orevenban,useofcertainfeatures.Wedothistokeepcodesimpleandtoavoidthevariouscommonerrorsandproblemsthatthesefeaturescancause.Thisguideliststhesefeaturesandexplainswhytheiruseisrestricted.
Open-sourceprojectsdevelopedbyGoogleconformtotherequirementsinthisguide.
NotethatthisguideisnotaC++tutorial:
weassumethatthereaderisfamiliarwiththelanguage.
Ingeneral,every
.cc
fileshouldhaveanassociated
.h
file.Therearesomecommonexceptions,suchasunittestsandsmall
filescontainingjusta
main()
function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
Allheaderfilesshouldhave
#define
guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe
<
PROJECT>
_<
PATH>
FILE>
_H_.
Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'
ssourcetree.Forexample,thefile
foo/src/bar/baz.h
inproject
foo
shouldhavethefollowingguard:
#ifndefFOO_BAR_BAZ_H_
#defineFOO_BAR_BAZ_H_
...
#endif//FOO_BAR_BAZ_H_
HeaderFileDependencies
Don'
tusean
#include
whenaforwarddeclarationwouldsuffice.
Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.
Youcansignificantlyreducethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusesthe
File
classinwaysthatdonotrequireaccesstothedeclarationofthe
class,yourheaderfilecanjustforwarddeclare
classFile;
insteadofhavingto
#include"
file/base/file.h"
.
Howcanweuseaclass
Foo
inaheaderfilewithoutaccesstoitsdefinition?
∙Wecandeclaredatamembersoftype
Foo*
or
Foo&
∙Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftype
Foo.(Oneexceptionisifanargument
constFoo&
hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)
∙Wecandeclarestaticdatamembersoftype
Foo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.
Ontheotherhand,youmustincludetheheaderfilefor
ifyourclasssubclasses
orhasadatamemberoftype
Foo.
Sometimesitmakessensetohavepointer(orbetter,
scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.
Ofcourse,
filestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.
Note:
Ifyouuseasymbol
inyoursourcefile,youshouldbringinadefinitionfor
yourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.Oneexceptionisif
isusedin
myfile.cc,it'
sokto#include(orforward-declare)
in
myfile.h,insteadof
myfile.cc.
InlineFunctions
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
Youmayusefilenameswitha
-inl.h
suffixtodefinecomplexinlinefunctionswhenneeded.
Thedefinitionofaninlinefunctionneedstobeinaheaderfile,sothatthecompilerhasthedefinitionavailableforinliningatthecallsites.However,implementationcodeproperlybelongsin
files,andwedonotliketohavemuchactualcodein
filesunlessthereisareadabilityorperformanceadvantage.
Ifaninlinefunctiondefinitionisshort,withverylittle,ifany,logicinit,youshouldputthecodeinyour
file.Forexample,accessorsandmutatorsshouldcertainlybeinsideaclassdefinition.Morecomplexinlinefunctionsmayalsobeputina
filefortheconvenienceoftheimplementerandcallers,thoughifthismakesthe
filetoounwieldyyoucaninsteadputthatcodeinaseparate
file.Thisseparatestheimp