下载
加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 Overview of the New C++ (C++0x)

Overview of the New C++ (C++0x).pdf

Overview of the New C++ (C++0x)

bruce2004
2011-10-21 0人阅读 举报 0 0 0 暂无简介

简介:本文档为《Overview of the New C++ (C++0x)pdf》,可适用于IT/计算机领域

artimaScottMeyersPresentationMaterialsTheNewCOverviewof(Cx)OverviewoftheNewC(Cx)ArtimaPressisanimprintofArtima,IncPOBox,WalnutCreek,CaliforniaCopyright©ScottMeyersAllrightsreservedFirstversionpublishedApril,ThisversionpublishedApril,ProducedintheUnitedStatesofAmericaCoverphotobyStephanJockelUsedwithpermissionNopartofthispublicationmaybereproduced,modified,distributed,storedinaretrievalsystem,republished,displayed,orperformed,forcommercialornoncommercialpurposesorforcompensationofanykindwithoutpriorwrittenpermissionfromArtima,IncThisPDFeBookispreparedexclusivelyforitspurchaser,whomayuseitforpersonalpurposesonly,asdescribedbytheArtimaeBooklicense(http:wwwartimacomebooklicensehtml)Inaddition,thepurchasermaymodifythisPDFeBooktohighlightsections,addcommentsandannotations,etc,exceptthatthe“Fortheexclusiveuseof”textthatidentifiesthepurchasermaynotbemodifiedinanywayAllinformationandmaterialsinthiseBookareprovided“asis”andwithoutwarrantyofanykindTheterm“Artima”andtheArtimalogoaretrademarksorregisteredtrademarksofArtima,IncAllothercompanyandorproductnamesmaybetrademarksorregisteredtrademarksoftheirownersOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedLastRevised:ScottMeyers,PhDSoftwareDevelopmentConsultantsmeyersaristeiacomVoice:http:wwwaristeiacomFax:OverviewoftheNewC(Cx)ThesearetheofficialnotesforScottMeyers’trainingcourse,“OverviewoftheNewC(Cx)”Thecoursedescriptionisathttp:wwwaristeiacomCxhtmlLicensinginformationisathttp:aristeiacomLicensinglicensinghtmlPleasesendbugreportsandimprovementsuggestionstosmeyersaristeiacomInthesenotes,referencestonumbereddocumentsprecededbyN(eg,N)arereferencestoCstandardizationdocumentsAllsuchdocumentsareavailableviahttp:wwwopenstdorgjtcscwgdocspapersReferencestosectionsofdraftCxareoftheformchaptersectionsubsectionSuchsymbolicnamesdon’tchangefromdrafttodraftReferencesalsogivesectionnumbersand(followingaslash)paragraphnumbersofspecificdraftsthosenumbersmayvaryacrossdraftsHencebasicfundamental(inN)referstothesectionwith(permanent)symbolicnamebasicfundamentalinparticulartosectionparagraphinNCommentsinbraces,suchasthis,areaimedatinstructorspresentingthecourseAllothercommentsshouldbehelpfulforbothinstructorsandpeoplereadingthenotesontheirownDayusuallyendssomewhereinthediscussionoftheCxconcurrencyAPIDayusuallygoestotheendofthelibrarymaterialOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideOverviewIntroductionHistory,vocabulary,quickCCxcomparisonFeaturesforEverybodyauto,rangebasedfor,lambdas,threads,etcLibraryEnhancementsReallymorefeaturesforeverybodyTRbasedfunctionality,forwardlist,uniqueptr,etcFeaturesforClassAuthorsMovesemantics,perfectforwarding,delegatinginheritingctors,etcFeaturesforLibraryAuthorsVariadictemplates,decltype,etcYetMoreFeaturesRemovedandDeprecatedFeaturesFurtherInformationThiscourseisanoverview,sothereisn’ttimetocoverthedetailsonmostfeaturesIngeneral,thefeaturesearlierinthecourse(theonesapplicabletomoreprogrammers)getmorethoroughtreatmentsthanthefeatureslaterinthecourseRvaluereferencesaren’tlistedonthispage,becauseit’spartofmovesemanticsOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideHistoryandVocabulary:ISOCStandardofficiallyadopted(“C”)pages:TC(“TechnicalCorrigendum”)published(“C”)BugfixesforCpages:TR(Library“TechnicalReport”)publishedlikelynewcomponentsforthestandardlibraryOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideHistoryandVocabulary:DraftfornewCstandard(“Cx”)achievesCDstatusTRderivedcomponentsplusmuchmorepages:(Limited)Cxfeatureavailabilitybecomescommon:RatificationofnewstandardexpectedFinalDraftInternationalStandard(“FDIS”)approvedinMarchpages“Cx”noweffectivelyacodename:TRAdditionallikelyfuturestandardlibrarycomponentsAnoverviewofsupportforCxfeaturesinvariouscompilersisavailableathttp:wwwaristeiacomCxCxFeatureAvailabilityhtmStephanTLavavejnotes()that“TheBoost::FileSystemlibrarywastheonlythingincorporatedintoTRbeforeworkonitwaspaused”OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideSampleCodeCaveatSomeofthecodeinthiscourseisuntested:(Compilersdon’tsupportallfeaturesorcombinationsoffeaturesIbelievethecodeiscorrect,butIoffernoguaranteeOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCopyingvsMovingChasalwayssupportedcopyingobjectstate:Copyconstructors,copyassignmentoperatorsCxaddssupportforrequeststomoveobjectstate:Widgetwcopyw’sstatetowWidgetw(w)Widgetw…movew’sstatetowWidgetw(std::move(w))Note:wcontinuestoexistinavalidstateaftercreationofwww’sstatewcopyofw’sstateww’sstatewThediagramsonthisslidemakeupaPowerPointanimationOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCopyingvsMovingTemporaryobjectsareprimecandidatesformoving:typedefstd::vector<T>TVecTVeccreateTVec()factoryfunctionTVecvt…vt=createTVec()inC,copyreturnvaluetovt,thendestroyreturnvaluecreateTVecTVecTTT…TTTvtTTT…TTTThediagramsonthisslidemakeupaPowerPointanimationInthisdiscussion,IuseacontainerofT,ratherthanspecifyingaparticulartype,eg,containerofstringorcontainerofintThemotivationformovesemanticsislargelyindependentofthetypesinvolved,althoughthelargerandmoreexpensivethetypesaretocopy,thestrongerthecaseformovingovercopyingOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCopyingvsMovingCxturnssuchcopyoperationsintomoverequests:TVecvt…vt=createTVec()implicitmoverequestinCxcreateTVecTVecTTT…TTTvtThediagramsonthisslidemakeupaPowerPointanimationOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCopyingvsMovingMovesemanticsexaminedindetaillater,but:MovingakeynewCxideaUsuallyanoptimizationofcopyingMoststandardtypesinCxaremoveenabledTheysupportmoverequestsEg,STLcontainersSometypesaremoveonly:Copyingprohibited,butmovingisallowedEg,streamobjects,std::threadobjects,std::uniqueptr,etcOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideSampleCvsCxProgramListthemostcommonwordsinasetoftextfilescountWordsAliceinWonderlandtxtWarandPeacetxtDraculatxtTheKamaSutratxtTheIliadtxtwordsfoundMostcommon:theandoftoainhishethatwaswithIhadasnotherisatonforThedatashownisfromtheplaintextversionsofthelistedbooksasdownloadedfromProjectGutenberg(http:wwwgutenbergorg)OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:C#include<cstdio>easierthaniostreamforformattedoutput#include<iostream>#include<iterator>#include<string>#include<fstream>#include<algorithm>#include<vector>#include<map>typedefstd::map<std::string,std::sizet>WordCountMapTypeWordCountMapTypewordsInFile(constchar*constfileName)foreachword{infile,returnstd::ifstreamfile(fileName)#ofWordCountMapTypewordCountsoccurrencesfor(std::stringwordfile>>word){wordCountsword}returnwordCounts}ItwouldbebettersoftwareengineeringtohavewordsInFilecheckthefilenameforvalidityandthencallanotherfunction(eg,"wordsInStream")todotheactualcounting,buttheresultingcodegetsabitmorecomplicatedintheserialcase(C)andyetmorecomplicatedintheconcurrentcase(Cx),sotokeepthisexampleprogramsimpleandfocusedonCxfeatures,weassumethateverypassedfilenameislegitimate,ie,weembracethe"nothingcouldpossiblygowrong"assumptionOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:CstructPtrPairndGT{comparendtemplate<typenameIt>componentsofbooloperator()(Itit,Itit)const{returnit>second>it>second}pointedtopairs}template<typenameMapIt>printnmostvoidshowCommonWords(MapItbegin,MapItend,conststd::sizetn)commonwords{inbegin,end)typedefstd::vector<MapIt>TempContainerTypetypedeftypenameTempContainerType::iteratorIterTypeTempContainerTypewordIterswordItersreserve(std::distance(begin,end))for(MapIti=begini!=endi)wordIterspushback(i)IterTypesortedRangeEnd=wordItersbegin()nstd::partialsort(wordItersbegin(),sortedRangeEnd,wordItersend(),PtrPairndGT())for(IterTypeit=wordItersbegin()it!=sortedRangeEndit){std::printf("sun",(*it)>firstcstr(),(*it)>second)}}UsingrangeinitializationforwordIters(ie,“TempContainerTypewordIters(begin,end)”)wouldbeincorrect,becausewewantwordIterstoholdtheiteratorsthemselves,notwhattheypointtoTheuseof“u”toprintanobjectoftypestd::sizetistechnicallyincorrect,becausethereisnoguaranteethatstd::sizetisoftypeunsigned(Itcouldbeeg,unsignedlong)Thetechnicallyportablesolutionisprobablytousethe“lu”formatspecifierandtocast(it*)>secondtounsignedlong(ortoreplaceuseofprintfwithiostreams),butI’mtakingthelazywayoutandignoringtheissueExceptinthisnote:)OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:Cintmain(intargc,constchar**argv)takelistoffilenamesoncommandline,{printmostcommonwordswithinWordCountMapTypewordCountsfor(intargNum=argNum<argcargNum){constWordCountMapTyperesults=copymapreturnedbywordsInFile(argvargNum)wordsInFile(modulocompileroptimization)for(WordCountMapType::constiteratori=resultsbegin()i!=resultsend()i){wordCountsi>first=i>second}}std::cout<<wordCountssize()<<"wordsfoundMostcommon:n"conststd::sizetmaxWordsToShow=showCommonWords(wordCountsbegin(),wordCountsend(),std::min(wordCountssize(),maxWordsToShow))}resultsisinitializedbycopyconstructor,which,becauseWordCountMapTypeisamapholdingstrings,couldbequiteexpensiveBecausethisisaninitialization(ratherthananassignment),compilersmayoptimizethecopyoperationawayTechnically,maxWordsToShowshouldbeoftypeWordCountMapType::sizetypeinsteadofstd::sizet,becausethereisnoguaranteethatthesearethesametype(andiftheyarenot,thecalltostd::minlikelywon’tcompile),butIamunawareofanyimplementationswheretheyaredifferenttypes,andusingtheofficiallycorrectformcausesformattingproblemsinthesidebysideprogramcomparisoncomingupinafewslides,soI’mcuttingacornerhereOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:Cx#include<cstdio>#include<iostream>#include<iterator>#include<string>#include<fstream>#include<algorithm>#include<vector>#include<unorderedmap>#include<future>usingWordCountMapType=std::unorderedmap<std::string,std::sizet>WordCountMapTypewordsInFile(constchar*constfileName)foreachword{infile,returnstd::ifstreamfile(fileName)#ofWordCountMapTypewordCountsoccurrencesfor(std::stringwordfile>>word){wordCountsword}returnwordCounts}OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:Cxtemplate<typenameMapIt>printnmostvoidshowCommonWords(MapItbegin,MapItend,conststd::sizetn)commonwords{inbegin,end)typedefstd::vector<MapIt>TempContainerTypetypedeftypenameTempContainerType::iteratorIterTypestd::vector<MapIt>wordIterswordItersreserve(std::distance(begin,end))for(autoi=begini!=endi)wordIterspushback(i)autosortedRangeEnd=wordItersbegin()nstd::partialsort(wordItersbegin(),sortedRangeEnd,wordItersend(),(MapItit,MapItit){returnit>second>it>second})for(autoit=wordIterscbegin()it!=sortedRangeEndit){std::printf("szun",(*it)>firstcstr(),(*it)>second)}}sortedRangeEndisinitializedwiththeresultofanexpressionusingbegin,notcbegin,becausesortedRangeEndwilllaterbepassedtopartialsort,andpartialsortinstantiationwillfailwithamixtureofiteratorsandconstiteratorsThebeginandenditeratorsinthatcallmustbeiterators(notconstiterators),becausepartialsortwillbemovingthingsaroundzisaformatspecifier(addedinC)Followedbyu,itcorrectlyprintsvariablesoftypesizetOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideCountingWordsAcrossFiles:Cxintmain(intargc,constchar**argv)takelistoffilenamesoncommandline,{printmostcommonwordswithinprocessfilesconcurrentlystd::vector<std::future<WordCountMapType>>futuresfor(intargNum=argNum<argcargNum){futurespushback(std::async(={returnwordsInFile(argvargNum)}))}WordCountMapTypewordCountsfor(autof:futures){constautoresults=fget()movemapreturnedbywordsInFilefor(constautowordCount:results){wordCountswordCountfirst=wordCountsecond}}std::cout<<wordCountssize()<<"wordsfoundMostcommon:n"conststd::sizetmaxWordsToShow=showCommonWords(wordCountsbegin(),wordCountsend(),std::min(wordCountssize(),maxWordsToShow))}ThiscodehasthemainthreadwaitforeachfiletobeprocessedonaseparatethreadratherthanprocessingoneofthefilesitselfThat’sjusttokeeptheexamplesimpleOverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideComparison#include<cstdio>#include<iostream>#include<iterator>#include<string>#include<fstream>#include<algorithm>#include<vector>#include<map>typedefstd::map<std::string,std::sizet>WordCountMapTypeWordCountMapTypewordsInFile(constchar*constfileName){std::ifstreamfile(fileName)WordCountMapTypewordCountsfor(std::stringwordfile>>word){wordCountsword}returnwordCounts}#include<cstdio>#include<iostream>#include<iterator>#include<string>#include<fstream>#include<algorithm>#include<vector>#include<unorderedmap>#include<future>usingWordCountMapType=std::unorderedmap<std::string,std::sizet>WordCountMapTypewordsInFile(constchar*constfileName){std::ifstreamfile(fileName)WordCountMapTypewordCountsfor(std::stringwordfile>>word){wordCountsword}returnwordCounts}OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideComparisonstructPtrPairndGT{template<typenameIt>booloperator()(Itit,Itit)const{returnit>second>it>second}}template<typenameMapIt>voidshowCommonWords(MapItbegin,MapItend,conststd::sizetn){typedefstd::vector<MapIt>TempContainerTypetypedeftypenameTempContainerType::iteratorIterTypeTempContainerTypewordIterswordItersreserve(std::distance(begin,end))for(MapIti=begini!=endi)wordIterspushback(i)IterTypesortedRangeEnd=wordItersbegin()nstd::partialsort(wordItersbegin(),sortedRangeEnd,wordItersend(),PtrPairndGT())for(IterTypeit=wordItersbegin()it!=sortedRangeEndit){std::printf("sun",(*it)>firstcstr(),(*it)>second)}}template<typenameMapIt>voidshowCommonWords(MapItbegin,MapItend,conststd::sizetn){std::vector<MapIt>wordIterswordItersreserve(std::distance(begin,end))for(autoi=begini!=endi)wordIterspushback(i)autosortedRangeEnd=wordItersbegin()nstd::partialsort(wordItersbegin(),sortedRangeEnd,wordItersend(),(MapItit,MapItit){returnit>second>it>second})for(autoit=wordIterscbegin()it!=sortedRangeEndit){std::printf("szun",(*it)>firstcstr(),(*it)>second)}}OverviewoftheNewC(Cx)ScottMeyers,SoftwareDevelopmentConsultanthttp:wwwaristeiacom©ScottMeyers,allrightsreservedSlideComparisonintmain(intargc,constchar**argv){WordCountMapTypewordCountsfor(intargNum=argNum<argcargNum){constWordCountMapTyperesults=wordsInFile(argvargNum)for(WordCountMapType::constiteratori=resultsbegin()i!=resultsend()i){wordCountsi>first=i>second}}std::cout<<wordCountssize()<<"wordsfoundM

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/49

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利