Google的C++编码规范Word文档格式.docx
《Google的C++编码规范Word文档格式.docx》由会员分享,可在线阅读,更多相关《Google的C++编码规范Word文档格式.docx(13页珍藏版)》请在冰豆网上搜索。
![Google的C++编码规范Word文档格式.docx](https://file1.bdocx.com/fileroot1/2022-12/12/df487e25-a476-42ce-9dc2-76742758f40e/df487e25-a476-42ce-9dc2-76742758f40e1.gif)
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.
Ingeneral,every
.cc
fileshouldhaveanassociated
.h
file.Therearesomecommonexceptions,suchasunittestsandsmall.cc
filescontainingjusta
main()
function.
Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.
Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.
The#defineGuard
Allheaderfilesshouldhave
#define
guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe<
PROJECT>
_<
PATH>
FILE>
_H_.
HeaderFileDependencies
Don'
tusean
#include
whenaforwarddeclarationwouldsuffice.
InlineFunctions
Definefunctionsinlineonlywhentheyaresmall,say,10linesorless.
The-inl.hFiles
Youmayusefilenameswitha
-inl.h
suffixtodefinecomplexinlinefunctionswhenneeded.
FunctionParameterOrdering
Whendefiningafunction,parameterorderis:
inputs,thenoutputs.
Usestandardorderforreadabilityandtoavoidhiddendependencies:
Clibrary,C++library,otherlibraries'
.h,yourproject'
s
.h.
Namespaces
Unnamednamespacesin
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.
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
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.
Prefersmallandfocusedfunctions.
TherearevarioustricksandutilitiesthatweusetomakeC++codemorerobust,andvariouswaysweuseC++thatmaydifferfromwhatyouseeelsewhere.
SmartPointers
Ifyouactuallyneedpointersemantics,
scoped_ptr
isgreat.Youshouldonlyuse
std:
:
tr1:
shared_ptr
underveryspecificconditions,suchaswhenobjectsneedtobeheldbySTLcontainers.Youshouldneveruse
auto_ptr.
Use
cpplint.py
todetectstyleerrors.
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