Google的C++编码规范Word文档格式.docx

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

Google的C++编码规范Word文档格式.docx

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

Google的C++编码规范Word文档格式.docx

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'

.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

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

当前位置:首页 > 高等教育 > 军事

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

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