谷歌C++编码规范 Google C++ Style Guide.docx

上传人:b****5 文档编号:5610997 上传时间:2022-12-29 格式:DOCX 页数:60 大小:62.82KB
下载 相关 举报
谷歌C++编码规范 Google C++ Style Guide.docx_第1页
第1页 / 共60页
谷歌C++编码规范 Google C++ Style Guide.docx_第2页
第2页 / 共60页
谷歌C++编码规范 Google C++ Style Guide.docx_第3页
第3页 / 共60页
谷歌C++编码规范 Google C++ Style Guide.docx_第4页
第4页 / 共60页
谷歌C++编码规范 Google C++ Style Guide.docx_第5页
第5页 / 共60页
点击查看更多>>
下载资源
资源描述

谷歌C++编码规范 Google C++ Style Guide.docx

《谷歌C++编码规范 Google C++ Style Guide.docx》由会员分享,可在线阅读,更多相关《谷歌C++编码规范 Google C++ Style Guide.docx(60页珍藏版)》请在冰豆网上搜索。

谷歌C++编码规范 Google C++ Style Guide.docx

谷歌C++编码规范GoogleC++StyleGuide

GoogleC++StyleGuide

Revision3.180

BenjyWeinberger

CraigSilverstein

GregoryEitzmann

MarkMentovai

TashanaLandray

Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:

▽.Youmaytoggleallsummarieswiththebigarrowbutton:

▽Toggleallsummaries

TableofContents

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

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.

Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.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.hfiletooun

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 能源化工

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1