Google C++ Style GuideWord格式.docx
- 文档编号:6235843
- 上传时间:2023-05-06
- 格式:DOCX
- 页数:74
- 大小:59.67KB
Google C++ Style GuideWord格式.docx
《Google C++ Style GuideWord格式.docx》由会员分享,可在线阅读,更多相关《Google C++ Style GuideWord格式.docx(74页珍藏版)》请在冰点文库上搜索。
TableofContents
HeaderFiles
The#defineGuardHeaderFileDependenciesInlineFunctionsThe-inl.hFilesFunctionParameterOrderingNamesandOrderofIncludes
Scoping
NamespacesNestedClassesNonmember,StaticMember,andGlobalFunctionsLocalVariablesGlobalVariables
Classes
DoingWorkinConstructorsDefaultConstructorsExplicitConstructorsCopyConstructorsStructsvs.ClassesInheritanceMultipleInheritanceInterfacesOperatorOverloadingAccessControlDeclarationOrderWriteShortFunctions
Google-SpecificMagic
SmartPointerscpplint
OtherC++Features
ReferenceArgumentsFunctionOverloadingDefaultArgumentsVariable-LengthArraysandalloca()FriendsExceptionsRun-TimeTypeInformation(RTTI)CastingStreamsPreincrementandPredecrementUseofconstIntegerTypes64-bitPortabilityPreprocessorMacros0andNULLsizeofBoost
Naming
GeneralNamingRulesFileNamesTypeNamesVariableNamesConstantNamesFunctionNamesNamespaceNamesEnumeratorNamesMacroNamesExceptionstoNamingRules
Comments
CommentStyleFileCommentsClassCommentsFunctionCommentsVariableCommentsImplementationCommentsPunctuation,SpellingandGrammarTODOComments
Formatting
LineLengthNon-ASCIICharactersSpacesvs.TabsFunctionDeclarationsandDefinitionsFunctionCallsConditionalsLoopsandSwitchStatementsPointerandReferenceExpressionsBooleanExpressionsReturnValuesVariableandArrayInitializationPreprocessorDirectivesClassFormatInitializerListsNamespaceFormattingHorizontalWhitespaceVerticalWhitespace
ExceptionstotheRules
ExistingNon-conformantCodeWindowsCode
Overview
ImportantNote
DisplayingHiddenDetailsinthisGuide
▽Thisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"
Hooray"
appearbelow.
link
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.
Ingeneral,every.ccfileshouldhaveanassociated.hfile.Therearesomecommonexceptions,suchasunittestsandsmall.ccfilescontainingjustamain()function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
▽Allheaderfilesshouldhave#defineguardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe<
PROJECT>
_<
PATH>
FILE>
_H_.
Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'
ssourcetree.Forexample,thefilefoo/src/bar/baz.hinprojectfooshouldhavethefollowingguard:
#ifndefFOO_BAR_BAZ_H_
#defineFOO_BAR_BAZ_H_
...
#endif//FOO_BAR_BAZ_H_
HeaderFileDependencies
▽Useforwarddeclarationstominimizeuseof#includein.hfiles.
Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.
Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusestheFileclassinwaysthatdonotrequireaccesstothedeclarationoftheFileclass,yourheaderfilecanjustforwarddeclareclassFile;
insteadofhavingto#include"
file/base/file.h"
.
HowcanweuseaclassFooinaheaderfilewithoutaccesstoitsdefinition?
∙WecandeclaredatamembersoftypeFoo*orFoo&
∙Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftypeFoo.
∙WecandeclarestaticdatamembersoftypeFoo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.
Ontheotherhand,youmustincludetheheaderfileforFooifyourclasssubclassesFooorhasadatamemberoftypeFoo.
Sometimesitmakessensetohavepointer(orbetter,scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.
Ofcourse,.ccfilestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.
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.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.Thiscanbeusedtokeepyourtemplatedefinitionseasytoread.
Donotforgetthata-inl.hfilerequiresa#defineguardjustlikeanyotherheaderfile.
FunctionParameterOrdering
▽Whendefiningafunction,parameterorderis:
inputs,thenoutputs.
ParameterstoC/C++functionsareeitherinputtothefunctio
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Google C+ Style Guide
![提示](https://static.bingdoc.com/images/bang_tan.gif)