Googlec++编程规范Word下载.docx

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

Googlec++编程规范Word下载.docx

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

Googlec++编程规范Word下载.docx

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.

Ingeneral,every 

.cc 

fileshouldhaveanassociated 

.h 

file.Therearesomecommonexceptions,suchasunittestsandsmall 

filescontainingjusta 

main() 

function.

Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.

Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.

The#defineGuard

Allheaderfilesshouldhave 

#define 

guardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe 

<

PROJECT>

_<

PATH>

FILE>

_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

Don'

tusean 

#include 

whenaforwarddeclarationwouldsuffice.

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

Youcansignificantlyreducethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusesthe 

File 

classinwaysthatdonotrequireaccesstothedeclarationofthe 

class,yourheaderfilecanjustforwarddeclare 

classFile;

 

insteadofhavingto 

#include"

file/base/file.h"

.

Howcanweuseaclass 

Foo 

inaheaderfilewithoutaccesstoitsdefinition?

∙Wecandeclaredatamembersoftype 

Foo* 

or 

Foo&

∙Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftype 

Foo.(Oneexceptionisifanargument 

constFoo&

hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)

∙Wecandeclarestaticdatamembersoftype 

Foo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.

Ontheotherhand,youmustincludetheheaderfilefor 

ifyourclasssubclasses 

orhasadatamemberoftype 

Foo.

Sometimesitmakessensetohavepointer(orbetter, 

scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.

Ofcourse, 

filestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.

Note:

Ifyouuseasymbol 

inyoursourcefile,youshouldbringinadefinitionfor 

yourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.Oneexceptionisif 

isusedin 

myfile.cc,it'

sokto#include(orforward-declare) 

in 

myfile.h,insteadof 

myfile.cc.

InlineFunctions

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

Youmayusefilenameswitha 

-inl.h 

suffixtodefinecomplexinlinefunctionswhenneeded.

Thedefinitionofaninlinefunctionneedstobeinaheaderfile,sothatthecompilerhasthedefinitionavailableforinliningatthecallsites.However,implementationcodeproperlybelongsin 

files,andwedonotliketohavemuchactualcodein 

filesunlessthereisareadabilityorperformanceadvantage.

Ifaninlinefunctiondefinitionisshort,withverylittle,ifany,logicinit,youshouldputthecodeinyour 

file.Forexample,accessorsandmutatorsshouldcertainlybeinsideaclassdefinition.Morecomplexinlinefunctionsmayalsobeputina 

filefortheconvenienceoftheimplementerandcallers,thoughifthismakesthe 

filetoounwieldyyoucaninsteadputthatcodeinaseparate 

file.Thisseparatestheimp

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

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

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

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