Google的C++编码规范.docx

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

Google的C++编码规范.docx

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

Google的C++编码规范.docx

Google的C++编码规范

GoogleC++StyleGuide

Revision3.180

BenjyWeinberger

CraigSilverstein

GregoryEitzmann

MarkMentovai

TashanaLandray

Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:

▶.Youmaytoggleallsummarieswiththebigarrowbutton:

▶ Toggleallsummaries

TableofContents

HeaderFiles

The#defineGuard HeaderFileDependencies InlineFunctions The-inl.hFilesFunctionParameterOrdering NamesandOrderofIncludes

Scoping

Namespaces NestedClasses Nonmember,StaticMember,andGlobalFunctions LocalVariablesStaticandGlobalVariables

Classes

DoingWorkinConstructors DefaultConstructors ExplicitConstructors CopyConstructorsStructsvs.Classes Inheritance MultipleInheritance Interfaces OperatorOverloadingAccessControl DeclarationOrder WriteShortFunctions

Google-SpecificMagic

SmartPointers cpplint

OtherC++Features

ReferenceArguments FunctionOverloading DefaultArguments Variable-LengthArraysandalloca()Friends Exceptions Run-TimeTypeInformation(RTTI) Casting StreamsPreincrementandPredecrement Useofconst IntegerTypes 64-bitPortability PreprocessorMacros0andNULL sizeof Boost C++0x

Naming

GeneralNamingRules FileNames TypeNames VariableNames ConstantNames FunctionNamesNamespaceNames EnumeratorNames MacroNames ExceptionstoNamingRules

Comments

CommentStyle FileComments ClassComments FunctionComments VariableCommentsImplementationComments Punctuation,SpellingandGrammar TODOComments DeprecationComments

Formatting

LineLength Non-ASCIICharacters Spacesvs.Tabs FunctionDeclarationsandDefinitionsFunctionCalls Conditionals LoopsandSwitchStatements PointerandReferenceExpressionsBooleanExpressions ReturnValues VariableandArrayInitialization PreprocessorDirectivesClassFormat ConstructorInitializerLists NamespaceFormatting HorizontalWhitespaceVerticalWhitespace

ExceptionstotheRules

ExistingNon-conformantCode WindowsCode

ImportantNote

DisplayingHiddenDetailsinthisGuide

Thisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"Hooray"appearbelow.

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

Allheaderfilesshouldhave #define guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe___H_.

HeaderFileDependencies

Don'tusean #include whenaforwarddeclarationwouldsuffice.

InlineFunctions

Definefunctionsinlineonlywhentheyaresmall,say,10linesorless.

The-inl.hFiles

Youmayusefilenameswitha -inl.h suffixtodefinecomplexinlinefunctionswhenneeded.

FunctionParameterOrdering

Whendefiningafunction,parameterorderis:

inputs,thenoutputs.

NamesandOrderofIncludes

Usestandardorderforreadabilityandtoavoidhiddendependencies:

Clibrary,C++library,otherlibraries' .h,yourproject's .h.

Scoping

Namespaces

Unnamednamespacesin .cc filesareencouraged.Withnamednamespaces,choosethenamebasedontheproject,andpossiblyitspath.Donotusea using-directive.

NestedClasses

Althoughyoumayusepublicnestedclasseswhentheyarepartofaninterface,considera namespace tokeepdeclarationsoutoftheglobalscope.

Nonmember,StaticMember,andGlobalFunctions

Prefernonmemberfunctionswithinanamespaceorstaticmemberfunctionstoglobalfunctions;usecompletelyglobalfunctionsrarely.

LocalVariables

Placeafunction'svariablesinthenarrowestscopepossible,andinitializevariablesinthedeclaration.

StaticandGlobalVariables

Staticorglobalvariablesofclasstypeareforbidden:

theycausehard-to-findbugsduetoindeterminateorderofconstructionanddestruction.

Classes

ClassesarethefundamentalunitofcodeinC++.Naturally,weusethemextensively.Thissectionliststhemaindosanddon'tsyoushouldfollowwhenwritingaclass.

DoingWorkinConstructors

Ingeneral,constructorsshouldmerelysetmembervariablestotheirinitialvalues.Anycomplexinitializationshouldgoinanexplicit Init() method.

DefaultConstructors

Youmustdefineadefaultconstructorifyourclassdefinesmembervariablesandhasnootherconstructors.Otherwisethecompilerwilldoitforyou,badly.

ExplicitConstructors

UsetheC++keyword explicit forconstructorswithoneargument.

CopyConstructors

Provideacopyconstructorandassignmentoperatoronlywhennecessary.Otherwise,disablethemwithDISALLOW_COPY_AND_ASSIGN.

Structsvs.Classes

Usea struct onlyforpassiveobjectsthatcarrydata;everythingelseisa class.

Inheritance

Compositionisoftenmoreappropriatethaninheritance.Whenusinginheritance,makeit public.

MultipleInheritance

Onlyveryrarelyismultipleimplementationinheritanceactuallyuseful.Weallowmultipleinheritanceonlywhenatmostoneofthebaseclasseshasanimplementation;allotherbaseclassesmustbe pureinterface classestaggedwiththeInterface suffix.

Interfaces

Classesthatsatisfycertainconditionsareallowed,butnotrequired,toendwithan Interface suffix.

OperatorOverloading

Donotoverloadoperatorsexceptinrare,specialcircumstances.

AccessControl

Makedatamembers private,andprovideaccesstothemthroughaccessorfunctionsasneeded(fortechnicalreasons,weallowdatamembersofatestfixtureclasstobe protected whenusing GoogleTest).Typicallyavariablewouldbecalledfoo_ andtheaccessorfunction foo().Youmayalsowantamutatorfunction set_foo().Exception:

 staticconst datamembers(typicallycalled kFoo)neednotbe private.

DeclarationOrder

Usethespecifiedorderofdeclarationswithinaclass:

 public:

 before private:

methodsbeforedatamembers(variables),etc.

WriteShortFunctions

Prefersmallandfocusedfunctions.

Google-SpecificMagic

TherearevarioustricksandutilitiesthatweusetomakeC++codemorerobust,andvariouswaysweuseC++thatmaydifferfromwhatyouseeelsewhere.

SmartPointers

Ifyouactuallyneedpointersemantics, scoped_ptr isgreat.Youshouldonlyuse std:

:

tr1:

:

shared_ptr underveryspecificconditions,suchaswhenobjectsneedtobeheldbySTLcontainers.Youshouldneveruse auto_ptr.

cpplint

Use cpplint.py todetectstyleerrors.

OtherC++Features

ReferenceArguments

Allparameterspassedbyreferencemustbelabeled const.

FunctionOverloading

Useoverloadedfunctions(includingconstructors)onlyifareaderlookingatacallsitecangetagoodideaofwhatishappeningwithouthavingtofirstfigureoutexactlywhichoverloadisbeingcalled.

DefaultArguments

Wedonotallowdefaultfunctionparameters,exceptinafewuncommonsituationsexplainedbelow.

Variable-LengthArraysandalloca()

Wedonotallowvariable-lengtharraysor alloca().

Friends

Weallowuseof friend classesandfunctions,withinreason.

Exceptions

WedonotuseC++exceptions.

Run-TimeTypeInformation(RTTI)

WedonotuseRunTimeTypeInformation(RTTI).

Casting

UseC++castslike static_cast<>().Donotuseothercastformatslike inty=(int)x; or inty=int(x);.

Streams

Usestreamsonlyforlogging.

PreincrementandPredecrement

Useprefixform(++i)oftheincrementanddecrementoperatorswithiteratorsandothertemplateobjects.

Useofconst

Westronglyrecommendthatyouuse const wheneveritmakessensetodoso.

IntegerTypes

Ofthebuilt-inC++integertypes,theonlyoneuse

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

当前位置:首页 > 成人教育 > 远程网络教育

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

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