谷歌C++编码规范.docx
- 文档编号:5408540
- 上传时间:2022-12-16
- 格式:DOCX
- 页数:59
- 大小:61.11KB
谷歌C++编码规范.docx
《谷歌C++编码规范.docx》由会员分享,可在线阅读,更多相关《谷歌C++编码规范.docx(59页珍藏版)》请在冰豆网上搜索。
谷歌C++编码规范
GoogleC++StyleGuide
Revision3.180
BenjyWeinberger
CraigSilverstein
GregoryEitzmann
MarkMentovai
TashanaLandray
Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:
▶.Youmaytoggleallsummarieswiththebigarrowbutton:
▶ Toggleallsummaries
TableofContents
HeaderFiles
The#defineGuard HeaderFileDependencies InlineFunctions The-inl.hFiles FunctionParameterOrdering NamesandOrderofIncludes
Scoping
Namespaces NestedClasses Nonmember,StaticMember,andGlobalFunctions LocalVariables StaticandGlobalVariables
Classes
DoingWorkinConstructors DefaultConstructors ExplicitConstructors CopyConstructors Structsvs.Classes Inheritance MultipleInheritance InterfacesOperatorOverloading AccessControl DeclarationOrder WriteShortFunctions
Google-SpecificMagic
SmartPointers cpplint
OtherC++Features
ReferenceArguments FunctionOverloading DefaultArguments Variable-LengthArraysandalloca() Friends Exceptions Run-TimeTypeInformation(RTTI)Casting Streams PreincrementandPredecrement Useofconst IntegerTypes 64-bitPortability PreprocessorMacros 0andNULL sizeof Boost C++0x
Naming
GeneralNamingRules FileNames TypeNames VariableNames ConstantNames FunctionNames NamespaceNames EnumeratorNames MacroNamesExceptionstoNamingRules
Comments
CommentStyle FileComments ClassComments FunctionComments VariableComments ImplementationComments Punctuation,SpellingandGrammarTODOComments DeprecationComments
Formatting
LineLength Non-ASCIICharacters Spacesvs.Tabs FunctionDeclarationsandDefinitions FunctionCalls Conditionals LoopsandSwitchStatementsPointerandReferenceExpressions BooleanExpressions ReturnValues VariableandArrayInitialization PreprocessorDirectives ClassFormatConstructorInitializerLists 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.
HeaderFiles
Ingeneral,every .cc fileshouldhaveanassociated .h file.Therearesomecommonexceptions,suchasunittestsandsmall .cc filescontainingjusta main() function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
link▽
Allheaderfilesshouldhave #define guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe
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
link▽
Don'tusean #include whenaforwarddeclarationwouldsuffice.
Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.
Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusesthe File classinwaysthatdonotrequireaccesstothedeclarationofthe 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.Thisseparatestheimpleme
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 谷歌 C+ 编码 规范