Googlec++编程规范.docx

上传人:b****5 文档编号:6015269 上传时间:2023-01-03 格式:DOCX 页数:60 大小:61.21KB
下载 相关 举报
Googlec++编程规范.docx_第1页
第1页 / 共60页
Googlec++编程规范.docx_第2页
第2页 / 共60页
Googlec++编程规范.docx_第3页
第3页 / 共60页
Googlec++编程规范.docx_第4页
第4页 / 共60页
Googlec++编程规范.docx_第5页
第5页 / 共60页
点击查看更多>>
下载资源
资源描述

Googlec++编程规范.docx

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

Googlec++编程规范.docx

Googlec++编程规范

GoogleC++StyleGuide

Revision3.199

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

HeaderFiles

Ingeneral,every .cc fileshouldhaveanassociated .h file.Therearesomecommonexceptions,suchasunittestsandsmall .cc filescontainingjusta main() function.

Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.

Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.

The#defineGuard

link▽

Allheaderfilesshouldhave #define guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe ___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

link▽

Don'tusean #include whenaforwarddeclarationwouldsuffice.

Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.

Youcansignificantlyreducethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.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.Thisseparatestheimp

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

当前位置:首页 > 求职职场 > 简历

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

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