



版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
GoogleC++StyleGuideRevision3.180BenjyWeinbergerCraigSilversteinGregoryEitzmannMarkMentovaiTashanaLandrayEachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:▽.Youmaytoggleallsummarieswiththebigarrowbutton:7ToggleallsummariesTableofContentsHeaderFilesThe#defineGuardHeaderFileDependenciesInlineFunctionsThe-inLhFilesFunctionParameter〇rderinaNamesandOrderofIncludesScopi、。NamespacesNestedClassesNonmember,StaticMember,andGlobalFunctionsLocalVariablesStaticandGlobalVariablesClassesDoinaWorkinConstructorsDefaultConstructorsExplicitConstructorsCopyConstructorsStructsvs.ClassesInheritanceMu用pieInhehtacceInterfacesOperatorOverloadinqAccessControlDeclarationOrderWriteShortFunctionsGoocle-SpecificMagicSmartPointerscpplintOtherC++FeaturesReferenceArgumentsFunction〇verloadingDefaultArgumentsVariable-LenEhArraysandalloca()FriendsExceptionsRun-TimeTypeInformation(RTTI)CastingStreamsPreincrementandPredecrementUseofconstInteserTypes64-bitPortabilityPreprocessorMacros〇andNULLsizeofBoostC++0xNamiriqGeneralNaminqRulesFileNamesTypeNamesVariableNamesConstantNamesFunctionNamesNamespaceNamesEnumeratorNamesMacroNamesExceptionstoNaminqRulesCommentsCommentStyleFileCommentsClassCommentsFunctionCommentsVariableCommentsImplementationCommentsPunctuation,SpellingandGrammarTODOCommentsDeprecationCommentsFormattingUneLenqthNon?ASCIICharactersSpacesvs.TabsFunctionDeclarationsandDefinitionsFunctionCallsConditionalsLoopsand
SwitchStatementsPointerandReferenceExpressionsBooleanExpressionsReturnValuesVariableandArrayInitializationPreprocessorDirectivesClassFormatConstructorInitializerListsNamespaceFormattinqHorizontalWhitespaceVerticalWhitespaceExceptionstotheRulesExistingNon-conformantCodeWindowsCodeImportantNoteDisplayingHiddenDetailsinthisGuidelinkVThisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.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〉!I.Toguaranteeuniqueness,theyshouldbebasedonthefullpathinaproject'ssourcetree.Forexample,thefilefoo/src/bar/baz.hinprojectfooshouldhavethefollowingguard:#ifndefFOOBAR_BAZH_4defineFOO_BAR_BAZ_H_#endif//FOO_BAR_BAZ_H_HeaderFileDependencieslinkVDon'tusean#includewhenaforwarddeclarationwouldsuffice.Whenyouincludeaheaderfileyouintroduceadependencythatwillcauseyourcodetoberecompiledwhenevertheheaderfilechanges.Ifyourheaderfileincludesotherheaderfiles,anychangetothosefileswillcauseanycodethatincludesyourheadertoberecompiled.Therefore,weprefertominimizeincludes,particularlyincludesofheaderfilesinotherheaderfiles.Youcansignificantlyminimizethenumberofheaderfilesyouneedtoincludeinyourownheaderfilesbyusingforwarddeclarations.Forexample,ifyourheaderfileusestheFileclassinwaysthatdonotrequireaccesstothedeclarationoftheFileclass,yourheaderfilecanjustforwarddeclareclassFile;insteadofhavingto#include/zfile/base/file.h”.HowcanweuseaclassFooinaheaderfilewithoutaccesstoitsdefinition?WecandeclaredatamembersoftypeFoo*orFoo&.Wecandeclare(butnotdefine)functionswitharguments,and/orreturnvalues,oftypeFoo.(OneexceptionisifanargumentFooorconstFoo&hasanon-explicit,one-argumentconstructor,inwhichcaseweneedthefulldefinitiontosupportautomatictypeconversion.)WecandeclarestaticdatamembersoftypeFoo.Thisisbecausestaticdatamembersaredefinedoutsidetheclassdefinition.Ontheotherhand,youmustincludetheheaderfileforFooifyourclasssubclassesFooorhasadatamemberoftypeFoo.Sometimesitmakessensetohavepointer(orbetter,scopedptr)membersinsteadofobjectmembers.However,thiscomplicatescodereadabilityandimposesaperformancepenalty,soavoiddoingthistransformationiftheonlypurposeistominimizeincludesinheaderfiles.Ofcourse,.ccfilestypicallydorequirethedefinitionsoftheclassestheyuse,andusuallyhavetoincludeseveralheaderfiles.Note:IfyouuseasymbolFooinyoursourcefile,youshouldbringinadefinitionforFooyourself,eitherviaan#includeorviaaforwarddeclaration.Donotdependonthesymbolbeingbroughtintransitivelyviaheadersnotdirectlyincluded.OneexceptionisifFooisusedinmyfile.cc,it'sokto#include(orforward-deciare)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-inl.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-ini.hfilesisfordefinitionsoffunctiontemplates.Thiscanbeusedtokeepyourtemplatedefinitionseasytoread.Donotforgetthata-ini.hfilerequiresa[defineguardjustlikeanyotherheaderfile.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.NamesandOrderofIncludeslinkVUsestandardorderforreadabilityandtoavoidhiddendependencies: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.hfilettincludedinsome.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<hash_map>4include<vector>#include"base/basictypes.h"#include"base/commandlineflags,h"#include"foo/public/bar.h"ScopingNamespaceslink▽Unnamednamespacesin.ccfilesareencouraged.Withnamednamespaces,choosethenamebasedontheproject,andpossiblyitspath.Donotuseausing-directive.Definition:Namespacessubdividetheglobalscopeintodistinct,namedscopes,andsoareusefulforpreventingnamecollisionsintheglobalscope.Pros:Namespacesprovidea(hierarchical)axisofnaming,inadditiontothe(alsohierarchical)nameaxisprovidedbyclasses.Forexample,iftwodifferentprojectshaveaclassFoointheglobalscope,thesesymbolsmaycollideatcompiletimeoratruntime.Ifeachprojectplacestheircodeinanamespace,projectl::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;}//Usesournamespace//Alldeclarationsarewithinthenamespacescope.//Alldeclarationsarewithinthenamespacescope.*}//namespaceHowever,file-scopedeclarationsthatareassociatedwithaparticularclassmaybedeclaredinthatclassastypes,staticdatamembersorstaticmemberfunctionsratherthanasmembersofanunnamednamespace.Terminatetheunnamednamespaceasshown,withacomment//namespace.Donotuseunnamednamespacesin.hfiles.NamedNamespacesNamednamespacesshouldbeusedasfollows:Namespaceswraptheentiresourcefileafterincludes,qflagsdefinitions/declarations,andforwarddeclarationsofclassesfromothernamespaces://Inthe.hfile? namespacemynamespace{
//Noticethelackofindentation,classMyClass{public:voidFoo();};}//namespacemynamespace//Inthe.ccfilenamespacemynamespace{//Definitionoffunctionsiswithinscopeofthenamespace,voidMyClass::Foo(){}//namespacemynamespaceThetypical.ccfilemighthavemorecomplexdetail,includingtheneedtoreferenceclassesinothernamespaces.#include"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;//Shortenaccesstosomecommon1yusednames(ina.hfile).namespacelibrarian{//Thefollowingaliasisavailabletoal1filesincluding//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.DoingWorkinConstructorslinkVIngeneral,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,gflaqswillnotyethavebeeninitialized.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.CopyConstructorslink▽Provideacopyconstructorandassignmentoperatoronlywhennecessary.Otherwise,disablethemwithDISALLOWCOPY_AND_ASSIGN.Definition:Thecopyconstructorandassignmentoperatorareusedtocreatecopiesofobjects.Thecopyconstructorisimplicitlyinvokedbythecompilerinsomesituations,e.g.passingobjectsbyvalue.
Pros:Copyconstructorsmakeiteasytocopyobjects.STLcontainersrequirethatallcontentsbecopyableandassignable.CopyconstructorscanbemoreefficientthanCopyFrom()-styleworkaroundsbecausetheycombineconstructionwithcopying,thecompilercanelidetheminsomecontexts,andtheymakeiteas
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度商業(yè)秘密合作轉(zhuǎn)讓合同協(xié)議
- 二零二五年度豬肉市場(chǎng)風(fēng)險(xiǎn)預(yù)警與應(yīng)對(duì)合同
- 二零二五年度社區(qū)服務(wù)兼職志愿者服務(wù)協(xié)議
- 二零二五年度成人外語(yǔ)培訓(xùn)機(jī)構(gòu)報(bào)名服務(wù)協(xié)議
- 二零二五年度手貨車車輛轉(zhuǎn)讓與汽車金融服務(wù)及市場(chǎng)推廣合同
- 2025年度游學(xué)旅游線路研發(fā)與推廣協(xié)議
- 2025年度珠寶首飾返傭金代理合同
- 2025年度混凝土班組勞務(wù)合作施工進(jìn)度合同
- 二零二五年度精裝修房屋買賣合同違約賠償標(biāo)準(zhǔn)
- 二零二五年度房產(chǎn)交易全程服務(wù)協(xié)議范本
- 尺寸鏈的計(jì)算表格
- 夏玉米套種辣椒技術(shù)
- 學(xué)術(shù)規(guī)范與寫作課件
- 絕緣電阻測(cè)試儀安全操作規(guī)程
- DB6101T 197-2022 藤蔓類尾菜堆肥技術(shù)規(guī)程
- 西藏房屋建筑工程竣工材料全套表格
- 量子力學(xué)英文課件格里菲斯Chapter4
- 鍋爐節(jié)能管理制度
- 2023年道路交通安全法實(shí)施條例
- 鹽城市殘疾人康復(fù)機(jī)構(gòu)認(rèn)定暫行辦法
- 護(hù)理不良事件管理、上報(bào)制度及流程
評(píng)論
0/150
提交評(píng)論