Google的C++编码规范Word文档格式.docx
- 文档编号:17979100
- 上传时间:2022-12-12
- 格式:DOCX
- 页数:13
- 大小:22.23KB
Google的C++编码规范Word文档格式.docx
《Google的C++编码规范Word文档格式.docx》由会员分享,可在线阅读,更多相关《Google的C++编码规范Word文档格式.docx(13页珍藏版)》请在冰豆网上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Google C+ 编码 规范
![提示](https://static.bdocx.com/images/bang_tan.gif)