谷歌C编码规范GoogleCStyleGuide_第1页
谷歌C编码规范GoogleCStyleGuide_第2页
谷歌C编码规范GoogleCStyleGuide_第3页
谷歌C编码规范GoogleCStyleGuide_第4页
已阅读5页,还剩52页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

GoogleC++StyleGuideRevision3.180BenjyWeinbergerCraigSilversteinGregoryEitzmannMarkMentovaiTashanaLandrayEachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:▽.Youmaytoggleallsummarieswiththebigarrowbutton:▽ToggleallsummariesTableofContentsHeaderFilesThe#defineGuardHeaderFileDependenciesInlineFunctionsThe-inl.hFilesFunctionParameterOrderingNamesandOrderofIncludesScocinqNamespacesNestedClassesNonmember,StaticMember,andGlobalFunctionsLocalVariablesStaticandGlobalVariablesClassesDoinqWorkinConstructorsDefaultConstructorsExplicitConstructorsCopyConstructorsStructsvs.ClassesInheritanceMultipleInheritanceInterfacesOperatorOverloadinqAccessControlDeclarationOrderWriteShortFunctionsGooqle-Spec计icMaqicSmartPointerscpplintOtherC++FeaturesReferenceArgumentsFunctionOverloadinqDefaultAraumentsVariable-LenathArraysandallocaOFriendsExceptionsRurnTimeTxceInformation(RTTI)CastingStreamsPreincrementandPredecrementUseofconstInteqerTypes64-bitPortabilityPreprocessorMacros0andNULLsizeofBoostC++0xNamingGeneralNaminqRulesFileNamesTypeNamesVariableNamesConstantNamesFunctionNamesNamespaceNamesEnumeratorNamesMacroNamesExceptionstoNaminqRulesCommentsCommentStyleFileCommentsClassCommentsFunctionCommentsVariableCommentsImplementationCommentsPunctuation,SpellinoandGrammarTODOCommentsDeprecationCommentsFormattingLineLenathNon-ASCIICharactersSpacesvs.TabsFunctionDeclarationsandDefinitionsFunctionCallsConditionalsLoopsandSwitchStatementsPointerandReferenceExpressionsBooleanExpressionsReturnValuesVariableandArrayInitializationPreprocessorDirectivesClassFormatConstructedInitializerListsNamespaceFormattin。HorizontalWhitespaceVerticalWhitespaceExceptionstotheRulesExistingNorvconformantCodeWindowsCodeImportantNoteDisplayingHiddenDetailsinthisGuidelinkVThisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"Hooray"appearbelow.Hooray!Nowyouknowyoucanexpandpointstogetmoredetails.Alternatively,there'san"expandall”atthetopofthisdocument.BackgroundC++isthemaindevelopmentlanguageusedbymanyofGoogle*sopen-sourceprojects.AseveryC++programmerknows,thelanguagehasmanypowerfulfeatures,butthispowerbringswithitcomplexity,whichinturncanmakecodemorebug-proneandhardertoreadandmaintain.Thegoalofthisguideistomanagethiscomplexitybydescribingindetailthedosanddon'tsofwritingC++code.TheserulesexisttokeepthecodebasemanageablewhilestillallowingcoderstouseC++languagefeaturesproductively.Style,alsoknownasreadability,iswhatwecalltheconventionsthatgovernourC++code.ThetermStyleisabitofamisnomer,sincetheseconventionscoverfarmorethanjustsourcefileformatting.Onewayinwhichwekeepthecodebasemanageableisbyenforcingconsistency.Itisveryimportantthatanyprogrammerbeabletolookatanother'scodeandquicklyunderstandit.Maintainingauniformstyleandfollowingconventionsmeansthatwecanmoreeasilyuse"pattern-matching“toinferwhatvarioussymbolsareandwhatinvariantsaretrueaboutthem.Creatingcommon,requiredidiomsandpatternsmakescodemucheasiertounderstand.Insomecasestheremightbegoodargumentsforchangingcertainstylerules,butwenonethelesskeepthingsastheyareinordertopreserveconsistency.AnotherissuethisguideaddressesisthatofC++featurebloat.C++isahugelanguagewithmanyadvancedfeatures.Insomecasesweconstrain,orevenban,useofcertainfeatures.Wedothistokeepcodesimpleandtoavoidthevariouscommonerrorsandproblemsthatthesefeaturescancause.Thisguideliststhesefeaturesandexplainswhytheiruseisrestricted.Open-sourceprojectsdevelopedbyGoogleconformtotherequirementsinthisguide.NotethatthisguideisnotaC++tutorial:weassumethatthereaderisfamiliarwiththelanguage.HeaderFilesIngeneral,every.ccfileshouldhaveanassociated.hfile.Therearesomecommonexceptions,suchasunittestsandsmall.ccfilescontainingjustamain()function.Correctuseofheaderfilescanmakeahugedifferencetothereadability,sizeandperformanceofyourcode.

Thefollowingruleswillguideyouthroughthevariouspitfallsofusingheaderfiles.The#defineGuardlinkVAllheaderfilesshouldhave#defineguardstopreventmultipleinclusion.Theformatofthesymbolnameshouldbe<PROJECT>_<PATH>_<FILE>』_.Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'ssourcetree.Forexample,thefilefoo/src/bar/baz.hinprojectfooshouldhavethefollowingguard:ttifndefFOOBARBAZH^defineFOO_BAR_BAZ_H#endif//FOO_BAR_BAZ_H_HeaderFileDependencieslinkVDon'tuseanttincludewhenaforwarddeclarationwouldsuffice.Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusestheFileclassinwaysthatdonotrequireaccesstothedeclarationoftheFileclass,yourheaderfilecanjustforwarddeclareclassFile;insteadofhavingtottincludez,file/base/file.h”.HowcanweuseaclassFooinaheaderfilewithoutaccesstoitsdefinition?WecandeclaredatamembersoftypeFoo*orFoo&.Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftypeFoo.(OneexceptionisifanargumentFooorconstFoo&hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)WecandeclarestaticdatamembersoftypeFoo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.Ontheotherhand,youmustincludetheheaderfileforFooifyourclasssubclassesFooorhasadatamemberoftypeFoo.

Sometimesitmakessensetohavepointer(orbetter,scoped_ptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.Ofcourse,.ccfilestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.Note:IfyouuseasymbolFooinyoursourcefile,youshouldbringinadefinitionforFooyourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.OneexceptionisifFooisusedinmyfile.cc,it'sokto#include(orforward-declare)Fooinmyfile.h,insteadofmyfile.cc.InlineFunctionslinkVDefinefunctionsinlineonlywhentheyaresmall,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.hFileslinkVYoumayusefilenameswitha-ini.hsuffixtodefinecomplexinlinefunctionswhenneeded.Thedefinitionofaninlinefunctionneedstobeinaheaderfile,sothatthecompilerhasthedefinitionavailableforinliningatthecallsites.However,implementationcodeproperlybelongsin.ccfiles,andwedonotliketohavemuchactualcodein.hfilesunlessthereisareadabilityorperformanceadvantage.Ifaninlinefunctiondefinitionisshort,withverylittle,ifany,logicinit,youshouldputthecodeinyour.hfile.Forexample,accessorsandmutatorsshouldcertainlybeinsideaclassdefinition.Morecomplexinlinefunctionsmayalsobeputina.hfilefortheconvenienceoftheimplementerandcallers,thoughifthismakesthe.hfiletoounwieldyyoucaninsteadputthatcodeinaseparate-ini.hfile.Thisseparatestheimplementationfromtheclassdefinition,whilestillallowingtheimplementationtobeincludedwherenecessary.Anotheruseof-inl.hfilesisfordefinitionsoffunctiontemplates.Thiscanbeusedtokeepyourtemplatedefinitionseasytoread.Donotforgetthata-ini.hfilerequiresa#dcfin。guardjustlikeanyotherheaderfile.FunctionParameterOrderinglinkVWhendefiningafunction,parameterorderis:inputs,thenoutputs.ParameterstoC/C++functionsareeitherinputtothefunction,outputfromthefunction,orboth.Inputparametersareusuallyvaluesorconstreferences,whileoutputandinput/outputparameterswillbenon-constpointers.Whenorderingfunctionparameters,putallinput-onlyparametersbeforeanyoutputparameters.Inparticular,donotaddnewparameterstotheendofthefunctionjustbecausetheyarenew;placenewinput-onlyparametersbeforetheoutputparameters.Thisisnotahard-and-fastrule.Parametersthatarebothinputandoutput(oftenclasses/structs)muddythewaters,and,asalways,consistencywithrelatedfunctionsmayrequireyoutobendtherule.NamesandOrderofIncludeslink/Usestandardorderforreadabilityandtoavoidhiddendependencies:Clibrary,C++library,otherlibraries'.h,yourproject's.h.Allofaproject'sheaderfilesshouldbelistedasdescentantsoftheproject'ssourcedirectorywithoutuseofUNIXdirectoryshortcuts.(thecurrentdirectory)or..(theparentdirectory).Forexample,google-awesome-project/src/base/logging,hshouldbeincludedas#include^base/logging.h"Indir/foo.cc,whosemainpurposeistoimplementortestthestuffindir2/foo2.h,orderyourincludesasfollows:dir2/foo2.h(preferredlocation—seedetailsbelow).Csystemfiles.C++systemfiles.Otherlibraries'.hfiles.

Yourproject's.hfiles.Thepreferredorderingreduceshiddendependencies.Wewanteveryheaderfiletobecompilableonitsown.Theeasiestwaytoachievethisistomakesurethateveryoneofthemisthefirst.hfile#includedinsome.cc.dir/foo.ccanddir2/foo2.hareofteninthesamedirectory(e.g.base/basictypes_test.ccandbase/basictypes.h),butcanbeindifferentdirectoriestoo.Withineachsectionitisnicetoordertheincludesalphabetically.Forexample,theincludesingoogle-awesome-project/src/foo/internal/fooserver.ccmightlooklikethis:#include"foo/public/fooserver.h"//Preferredlocation.#include<sys/types.h>#include<unistd.h>#include<hashmap>#include<vector>#includezzbase/basictypes,h”#include^base/commandlineflags,h”'include"foo/public/bar.h"ScopingNamespaceslinkVUnnamednamespacesin.ccfilesareencouraged.Withnamednamespaces,choosethenamebasedontheproject,andpossiblyitspath.Donotuseausing-directive.Definition:Namespacessubdividetheglobalscopeintodistinct,namedscopes,andsoareusefulforpreventingnamecollisionsintheglobalscope.Pros:Namespacesprovidea(hierarchical)axisofnaming,inadditiontothe(alsohierarchical)nameaxisprovidedbyclasses.Forexample,iftwodifferentprojectshaveaclassFoointheglobalscope,thesesymbolsmaycollideatcompiletimeoratruntime.Ifeachprojectplacestheircodeinanamespace,project1::Fooandproject2::Fooarenowdistinctsymbolsthatdonotcollide.Cons:

Namespacescanbeconfusing,becausetheyprovideanadditional(hierarchical)axisofnaming,inadditiontothe(alsohierarchical)nameaxisprovidedbyclasses.UseofunnamedspacesinheaderfilescaneasilycauseviolationsoftheC++OneDefinitionRule(ODR).Decision:Usenamespacesaccordingtothepolicydescribedbelow.UnnamedNamespacesUnnamednamespacesareallowedandevenencouragedin.ccfiles,toavoidruntimenamingconflicts:namespace{ //Thisisina.ccfile.*//Thecontentofanamespaceisnotindentedenum{kUnused,kEOF,kError}; //Commonlyusedtokens.boolAtEof(){returnpos_==kEOF;}//Usesournamespace1sEOF.*}//namespaceHowever,file-scopedeclarationsthatareassociatedwithaparticularclassmaybedeclaredinthatclassastypes,staticdatamembersorstaticmemberfunctionsratherthanasmembersofanunnamednamespace.Terminatetheunnamednamespaceasshown,withacomment//namespace.Donotuseunnamednamespacesin.hfiles.NamedNamespacesNamednamespacesshouldbeusedasfollows:Namespaceswraptheentiresourcefileafterincludes,qflagsdefinitions/declarations,andforwarddeclarationsofclassesfromothernamespaces://Inthe.hfilenamespacemynamespace{•//Alldeclarationsarewithinthenamespacescope.//Noticethe lack ofindentation.classMyClass {public:voidFoo();};}//namespacemynamespace

//Inthe.ccfilenamespacemynamespace//Definitionoffunctionsiswithinscopeofthenamespace,voidMyClass::Foo(){}//namespacemynamespaceThetypical.ccfilemighthavemorecomplexdetail,includingtheneedtoreferenceclassesinothernamespaces.itinclude"a.h*DEFINE_bool(someflag,false,“dummyflag*);classC;//ForwarddeclarationofclassCintheglobalspacea{classA;}//Forwarddeclarationofa::A.namespaceb{...codeforb... //Codegoesagainsttheleftmargin.}//namespacebDonotdeclareanythinginnamespacestd,notevenforwarddeclarationsofstandardlibraryclasses.Declaringentitiesinnamespacestdisundefinedbehavior,i.e.,notportable.Todeclareentitiesfromthestandardlibrary,includetheappropriateheaderfile.Youmaynotuseausing-directivetomakeallnamesfromanamespaceavailable.//Forbidden―Thispollutesthenamespace.usingnamespacefoo;Youmayuseausing-declarationanywhereina.ccfile,andinfunctions,methodsorclassesin.hfiles.//OKin.ccfiles.//Mustbeinafunction,methodorclassin.hfiles.using::foo::bar;Namespacealiasesareallowedanywhereina.ccfile,anywhereinsidethenamednamespacethatwrapsanentire.hfile,andinfunctionsandmethods.//Shortenaccesstosomecommonlyusednamesin.ccspacefbz=::foo::bar::baz;

//Shortenaccesstosomecommonlyusednames(ina.hfile),namespacelibrarian{//Thefollowingaliasisavailabletoallfilesincluding//thisheader(innamespacelibrarian)://aliasnamesshouldthereforebechosenconsistently//withinaspacepd_s=::pipeline_diagnostics::sidetable;inlinevoidmy_inline_function(){//namespacealiaslocaltoafunction(ormethod).namespacefbz=::foo::bar::baz;}//namespacelibrarianNotethatanaliasina.hfileisvisibletoeveryone#includingthatfile,sopublicheaders(thoseavailableoutsideaproject)andheaderstransitively#includedbythem,shouldavoiddefiningaliases,aspartofthegeneralgoalofkeepingpublicAPIsassmallaspossible.NestedClasseslinkVAlthoughyoumayusepublicnestedclasseswhentheyarepartofaninterface,consideranamespacetokeepdeclarationsoutoftheglobalscope.Definition:Aclasscandefineanotherclasswithinit;thisisalsocalledamemberclass.classFoo{private://Barisamemberclass,nestedwithinFoo.classBar{):};Pros:Thisisusefulwhenthenested(ormember)classisonlyusedbytheenclosingclass;makingitamemberputsitintheenclosingclassscoperatherthanpollutingtheouterscopewiththeclassname.Nestedclassescanbeforwarddeclaredwithintheenclosingclassandthendefinedinthe.ccfiletoavoidincludingthenestedclassdefinitionintheenclosingclassdeclaration,sincethenestedclassdefinitionisusuallyonlyrelevanttotheimplementation.Cons:Nestedclassescanbeforward-declaredonlywithinthedefinitionoftheenclosingclass.Thus,anyheaderfilemanipulatingaFoo::Bar*pointerwillhavetoincludethefullclassdeclarationforFoo.

Decision:Donotmakenestedclassespublicunlesstheyareactuallypartoftheinterface,e.g.,aclassthatholdsasetofoptionsforsomemethod.Nonmember,StaticMember,andGlobalFunctionslinkVPrefernonmemberfunctionswithinanamespaceorstaticmemberfunctionstoglobalfunctions;usecompletelyglobalfunctionsrarely.Pros:Nonmemberandstaticmemberfunctionscanbeusefulinsomesituations.Puttingnonmemberfunctionsinanamespaceavoidspollutingtheglobalnamespace.Cons:Nonmemberandstaticmemberfunctionsmaymakemoresenseasmembersofanewclass,especiallyiftheyaccessexternalresourcesorhavesignificantdependencies.Decision:Sometimesitisuseful,orevennecessary,todefineafunctionnotboundtoaclassinstance.Suchafunctioncanbeeitherastaticmemberoranonmemberfunction.Nonmemberfunctionsshouldnotdependonexternalvariables,andshouldnearlyalwaysexistinanamespace.Ratherthancreatingclassesonlytogroupstaticmemberfunctionswhichdonotsharestaticdata,usenamespacesinstead.Functionsdefinedinthesamecompilationunitasproductionclassesmayintroduceunnecessarycouplingandlink-timedependencieswhendirectlycalledfromothercompilationunits;staticmemberfunctionsareparticularlysusceptibletothis.Considerextractinganewclass,orplacingthefunctionsinanamespacepossiblyinaseparatelibrary.Ifyoumustdefineanonmemberfunctionanditisonlyneededinits.ccfile,useanunnamednamespaceorstaticlinkage(egstaticintFoo()(...))tolimititsscope.LocalVariableslinkVPlaceafunction'svariablesinthenarrowestscopepossible,andinitializevariablesinthedeclaration.C++allowsyoutodeclarevariablesanywhereinafunction.Weencourageyoutodeclaretheminaslocalascopeaspossible,andasclosetothefirstuseaspossible.Thismakesiteasierforthereadertofindthedeclarationandseewhattypethevariableisandwhatitwasinitializedto.Inparticular,initializationshouldbeusedinsteadofdeclarationandassignment,i;i=f(); //Bad-initializationseparatefromj=g();//Good-declarationhasinitialization.Notethatgccimplementsfor(inti=0;i<10;++i)correctly(thescopeofiisonlythescopeoftheforloop),soyoucanthenreuseiinanotherforloopinthesamescope.Italsocorrectlyscopesdeclarationsinifandwhilestatements,e.g.

while(constchar*p=strchr(str,'/'))str=p+1;Thereisonecaveat:ifthevariableisanobject,itsconstructorisinvokedeverytimeitentersscopeandiscreated,anditsdestructorisinvokedeverytimeitgoesoutofscope.//Inefficientimplementation:for(inti=0;i<1000000;++i){Foof;//Myctoranddtorgetcalled1000000timeseach.f.DoSomething(i);}Itmaybemoreefficienttodeclaresuchavariableusedinaloopoutsidethatloop:Foof;//Myctoranddtorgetcalledonceeach.for(inti=0;i<1000000;++i){f.DoSomething(i);StaticandGlobalVariableslinkVStaticorglobalvariablesofclasstypeareforbidden:theycausehard-to-findbugsduetoindeterminateorderofconstructionanddestruction.Objectswithstaticstorageduration,includingglobalvariables,staticvariables,staticclassmembervariables,andfunctionstaticvariables,mustbePlainOldData(POD):onlyints,chars,floats,orpointers,orarrays/structsofPOD.TheorderinwhichclassconstructorsandinitializersforstaticvariablesarecalledisonlypartiallyspecifiedinC++andcanevenchangefrombuildtobuild,whichcancausebugsthataredifficulttofind.Thereforeinadditiontobanningglobalsofclasstype,wedonotallowstaticPODvariablestobeinitializedwiththeresultofafunction,unlessthatfunction(suchasgetenv(),orgetpid())doesnotitselfdependonanyotherglobals.Likewise,theorderinwhichdestructorsarecalledisdefinedtobethereverseoftheorderinwhichtheconstructorswerecalled.Sinceconstructororderisindeterminate,soisdestructororder.Forexample,atprogram-endtimeastaticvariablemighthavebeendestroyed,butcodestillrunning-perhapsinanotherthread-triestoaccessitandfails.Orthedestructorforastatic'string'variablemightberunpriortothedestructorforanothervariablethatcontainsareferencetothatstring.AsaresultweonlyallowstaticvariablestocontainPODdata.Thisrulecompletelydisallowsvector(useCarraysinstead),orstring(useconstchar[]).Ifyouneedastaticorglobalvariableofaclasstype,considerinitializingapointer(whichwillneverbefreed),fromeitheryourmain()functionorfrompthread_once().Notethatthismustbearawpointer,nota“smart”pointer,sincethesmartpointer'sdestructorwillhavetheorder-of-destructorissuethatwearetryingtoavoid.

ClassesClassesarethefundamentalunitofcodeinC++.Naturally,weusethemextensively.Thissectionliststhemaindosanddon'tsyoushouldfollowwhenwritingaclass.DoingWorkinConstructorslinkJIngeneral,constructorsshouldmerelysetmembervariablestotheirinitialvalues.AnycomplexinitializationshouldgoinanexplicitInit()method.Definition:Itispossibletoperforminitializationinthebodyoftheconstructor.Pros:Convenienceintyping.Noneedtoworryaboutwhethertheclasshasbeeninitializedornot.Cons:Theproblemswithdoingworkinconstructorsare:Thereisnoeasywayforconstructorstosignalerrors,shortofusingexceptions(whichareforbidden).Iftheworkfails,wenowhaveanobjectwhoseinitializationcodefailed,soitmaybeanindeterminatestate.Iftheworkcallsvirtualfunctions,thesecallswillnotgetdispatchedtothesubclassimplementations.Futuremodificationtoyourclasscanquietlyintroducethisproblemevenifyourclassisnotcurrentlysubclassed,causingmuchconfusion.Ifsomeonecreatesaglobalvariableofthistype(whichisagainsttherules,butstill),theconstructorcodewillbecalledbeforemain(),possiblybreakingsomeimplicitassumptionsintheconstructorcode.Forinstance,qflagswillnotyethavebeeninitialized.Decision:Ifyourobjectrequiresnon-trivialinitialization,considerhavinganexplicitInit()method.Inparticular,constructorsshouldnotcallvirtualfunctions,attempttoraiseerrors,accesspotentiallyuninitializedglobalvariables,etc.DefaultConstructorslinkVYoumustdefineadefaultconstructorifyourclassdefinesmembervariablesandhasnootherconstructors.Otherwisethecompilerwilldoitforyou,badly.Definition:Thedefaultconstructoriscalledwhenwenewaclassobjectwithnoarguments.Itisalwayscalledwhencallingnew[](forarrays).Pros:Initializingstructuresbydefault,tohold"impossible'*values,makesdebuggingmucheasier.Cons:Extraworkforyou,thecodewriter.Decision:Ifyourclassdefinesmembervariablesandhasnootherconstructorsyoumustdefineadefaultconstructor(onethattakesnoarguments).Itshouldpreferablyinitializetheobjectinsuchawaythatitsinternalstateisconsistentandvalid.Thereasonforthisisthatifyouhavenootherconstructorsanddonotdefineadefaultconstructor,thecompilerwillgenerateoneforyou.Thiscompilergeneratedconstructormaynotinitializeyourobjectsensibly.Ifyourclassinheritsfromanexistingclassbutyouaddnonewmembervariables,youarenotrequiredtohaveadefaultconstructor.ExplicitConstructorslinkVUsetheC++keywordexplicitforconstructorswithoneargument.Definition:Normally,ifaconstructortakesoneargument,itcanbeusedasaconversion.Forinstance,ifyoudefineFoo::Foo(stringname)andthenpassastringtoafunctionthatexpectsaFoo,theconstructorwillbecalledtoconvertthestringintoaFooandwillpasstheFootoyourfunctionforyou.Thiscanbeconvenientbutisalsoasourceoftroublewhenthingsgetconvertedandnewobjectscreatedwithoutyoumeaningthemto.Declaringaconstructorexplicitpreventsitfrombeinginvokedimplicitlyasaconversion.Pros:Avoidsundesirableconversions.Cons:None.Decision:Werequireallsingleargumentconstructorstobeexplicit.Alwaysputexplicitinfrontofone-argumentconstructorsintheclassdefinition:explicitFoo(stringname);Theexceptioniscopyconstructors,which,intherarecaseswhenweallowthem,shouldprobablynotbeexplicit.Classesthatareintendedtobetransparentwrappersaroundotherclassesarealsoexceptions.Suchexceptionsshouldbeclearlymarkedwithcomments.CopyConstructorslinkVProvideacopyconstructorandassignmentoperatoronlywhennecessary.Otherwise,disablethemwithDISALLOW_COPY_AND_ASSIGN.Definition:Thecopyconstructorandassignmentoperatorareusedtocreatecopiesofobjects.Thecopyconstructorisimplicitlyinvokedbythecompilerinsomesituations,e.g.passingobjectsbyvalue.Pros:Copyconstructorsmakeiteasytocopyobjects.STLcontainersrequirethatallcontentsbecopyableandassignable.CopyconstructorscanbemoreefficientthanCopyFrom()-styleworkaroundsbecausetheycombineconstructionwithcopying,thecompilercanelidetheminsomecontexts,andtheymakeiteasiertoavoidheapallocation.

C

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论