




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
皮晨暉軟件081班ObjectlandscapesandlifetimesTechnically,OOPisjustaboutabstractdatatyping,inheritance,andpolymorphism,butotherissuescanbeatleastasimportant.Theremainderofthissectionwillcovertheseissues.Oneofthemostimportantfactorsisthewayobjectsarecreatedanddestroyed.Whereisthedataforanobjectandhowisthelifetimeoftheobjectcontrolled?Therearedifferentphilosophiesatworkhere.C++takestheapproachthatcontrolofefficiencyisthemostimportantissue,soitgivestheprogrammerachoice.Formaximumrun-timespeed,thestorageandlifetimecanbedeterminedwhiletheprogramisbeingwritten,byplacingtheobjectsonthestack(thesearesometimescalledautomaticorscopedvariables)orinthestaticstoragearea.Thisplacesapriorityonthespeedofstorageallocationandrelease,andcontrolofthesecanbeveryvaluableinsomesituations.However,yousacrificeflexibilitybecauseyoumustknowtheexactquantity,lifetime,andtypeofobjectswhileyou'rewritingtheprogram.Ifyouaretryingtosolveamoregeneralproblemsuchascomputer-aideddesign,warehousemanagement,orair-trafficcontrol,thisistoorestrictive.Thesecondapproachistocreateobjectsdynamicallyinapoolofmemorycalledtheheap.Inthisapproach,youdon'tknowuntilrun-timehowmanyobjectsyouneed,whattheirlifetimeis,orwhattheirexacttypeis.Thosearedeterminedatthespurofthemomentwhiletheprogramisrunning.Ifyouneedanewobject,yousimplymakeitontheheapatthepointthatyouneedit.Becausethestorageismanageddynamically,at(yī)run-time,theamountoftimerequiredtoallocat(yī)estorageontheheapissignificantlylongerthanthetimetocreatestorageonthestack.(Creatingstorageonthestackisoftenasingleassemblyinstructiontomovethestackpointerdown,andanothertomoveitbackup.)Thedynamicapproachmakesthegenerallylogicalassumptionthatobjectstendtobecomplicated,sotheextraoverheadoffindingstorageandreleasingthatstoragewillnothaveanimportantimpactonthecreationofanobject.Inaddition,thegreaterflexibilityisessentialtosolvethegeneralprogrammingproblem.Javausesthesecondapproach,exclusivelyHYPERLINK"../../../DocumentsandSettings/gg/LocalSettings/Temp/e/TIJ303.htm"\l"fn8#fn8"].Everytimeyouwanttocreateanobject,youusethenewkeywordtobuildadynamicinstanceofthatobject.There'sanotherissue,however,andthat'sthelifetimeofanobject.Withlanguagesthatallowobjectstobecreat(yī)edonthestack,thecompilerdetermineshowlongtheobjectlastsandcanautomat(yī)icallydestroyit.However,ifyoucreateitontheheapthecompilerhasnoknowledgeofitslifetime.InalanguagelikeC++,youmustdetermineprogrammat(yī)icallywhentodestroytheobject,whichcanleadtomemoryleaksifyoudon’tdoitcorrectly(andthisisacommonprobleminC++programs).Javaprovidesafeaturecalledagarbagecollectorthatautomaticallydiscoverswhenanobjectisnolongerinuseanddestroysit.Agarbagecollectorismuchmoreconvenientbecauseitreducesthenumberofissuesthat(yī)youmusttrackandthecodeyoumustwrite.Moreimportant,thegarbagecollectorprovidesamuchhigherlevelofinsuranceagainsttheinsidiousproblemofmemoryleaks(whichhasbroughtmanyaC++projecttoitsknees).Therestofthissectionlooksatadditionalfactorsconcerningobjectlifetimesandlandscapes.1.ThesinglyrootedhierarchyOneoftheissuesinOOPthat(yī)hasbecomeespeciallyprominentsincetheintroductionofC++iswhetherallclassesshouldultimatelybeinheritedfromasinglebaseclass.InJava(aswithvirtuallyallotherOOPlanguages)theansweris“yes”andthenameofthisultimat(yī)ebaseclassissimplyObject.Itturnsoutthatthebenefitsofthesinglyrootedhierarchyaremany.HYPERLINK"mailto:?Subject=%5bTIJ3%5dChap01_186"\o"SendBackTalkComment"Allobjectsinasinglyrootedhierarchyhaveaninterfaceincommon,sotheyareallultimatelythesametype.Thealternative(providedbyC++)isthatyoudon’tknowthateverythingisthesamefundamentaltype.Fromabackward-compatibilitystandpointthisfitsthemodelofCbetterandcanbethoughtofaslessrestrictive,butwhenyouwanttodofull-onobject-orientedprogrammingyoumustthenbuildyourownhierarchytoprovidethesameconveniencethat’sbuiltintootherOOPlanguages.Andinanynewclasslibraryyouacquire,someotherincompatibleinterfacewillbeused.Itrequireseffort(andpossiblymultipleinheritance)toworkthenewinterfaceintoyourdesign.Istheextra“flexibility”ofC++worthit?Ifyouneedit—ifyouhavealargeinvestmentinC—it’squitevaluable.Ifyou’restartingfromscratch,otheralternativessuchasJavacanoftenbemoreproductive.HYPERLINK"mailto:?Subject=%5bTIJ3%5dChap01_187"\o"SendBackTalkComment"Allobjectsinasinglyrootedhierarchy(suchasJavaprovides)canbeguaranteedtohavecertainfunctionality.Youknowyoucanperformcertainbasicoperationsoneveryobjectinyoursystem.Asinglyrootedhierarchy,alongwithcreatingallobjectsontheheap,greatlysimplifiesargumentpassing(oneofthemorecomplextopicsinC++).HYPERLINK"mailto:?Subject=%5bTIJ3%5dChap01_188"\o"SendBackTalkComment"Asinglyrootedhierarchymakesitmucheasiertoimplementagarbagecollector(whichisconvenientlybuiltintoJava).Thenecessarysupportcanbeinstalledinthebaseclass,andthegarbagecollectorcanthussendtheappropriatemessagestoeveryobjectinthesystem.Withoutasinglyrootedhierarchyandasystemtomanipulat(yī)eanobjectviaareference,itisdifficulttoimplementagarbagecollector.HYPERLINK"mailto:?Subject=%5bTIJ3%5dChap01_189"\o"SendBackTalkComment"Sincerun-timetypeinformationisguaranteedtobeinallobjects,you’llneverendupwithanobjectwhosetypeyoucannotdetermine.Thisisespeciallyimportantwithsystemleveloperations,suchasexceptionhandling,andtoallowgreaterflexibilityinprogramming.HYPERLINK"mailto:?Subject=%5bTIJ3%5dChap01_190"\o"SendBackTalkComment"2.CollectionlibrariesandsupportforeasycollectionuseBecauseacontainerisatoolthatyou’llusefrequently,itmakessensetohavealibraryofcontainersthatarebuiltinareusablefashion,soyoucantakeoneofftheshelfBecauseacontainerisatoolthatyou’llusefrequently,itmakessensetohavealibraryofcontainersthat(yī)arebuiltinareusablefashion,soyoucantakeoneofftheshelfandplugitintoyourprogram.Javaprovidessuchalibrary,whichshouldsatisfymostneeds.Downcastingvs.templates/genericsTomakethesecontainersreusable,theyholdtheoneuniversaltypeinJavathat(yī)waspreviouslymentioned:Object.ThesinglyrootedhierarchymeansthateverythingisanObject,soacontainerthatholdsObjectscanholdanything.Thismakescontainerseasytoreuse.Tousesuchacontainer,yousimplyaddobjectreferencestoit,andlat(yī)eraskforthemback.But,sincethecontainerholdsonlyObjects,whenyouaddyourobjectreferenceintothecontaineritisupcasttoObject,thuslosingitsidentity.Whenyoufetchitback,yougetanObjectreference,andnotareferencetothetypethatyouputin.Sohowdoyouturnitbackintosomethingthathastheusefulinterfaceoftheobjectthatyouputintothecontainer?Here,thecastisusedagain,butthistimeyou’renotcastinguptheinheritancehierarchytoamoregeneraltype,youcastdownthehierarchytoamorespecifictype.Thismannerofcastingiscalleddowncasting.Withupcasting,youknow,forexample,that(yī)aCircleisatypeofShapesoit’ssafetoupcast,butyoudon’tknowthatanObjectisnecessarilyaCircleoraShapesoit’shardlysafetodowncastunlessyouknowthat’swhatyou’redealingwith.It’snotcompletelydangerous,however,becauseifyoudowncasttothewrongthingyou’llgetarun-timeerrorcalledanexception,whichwillbedescribedshortly.Whenyoufetchobjectreferencesfromacontainer,though,youmusthavesomewaytorememberexactlywhattheyaresoyoucanperformaproperdowncast.Downcastingandtherun-timechecksrequireextratimefortherunningprogram,andextraeffortfromtheprogrammer.Wouldn’titmakesensetosomehowcreatethecontainersothatitknowsthetypesthatitholds,eliminatingtheneedforthedowncastandapossiblemistake?Thesolutionisparameterizedtypes,whichareclassesthat(yī)thecompilercanautomaticallycustomizetoworkwithparticulartypes.Forexample,withaparameterizedcontainer,thecompilercouldcustomizethatcontainersothatitwouldacceptonlyShapesandfetchonlyShapes.ParameterizedtypesareanimportantpartofC++,partlybecauseC++hasnosinglyrootedhierarchy.InC++,thekeywordthat(yī)implementsparameterizedtypesis“template.”Javacurrentlyhasnoparameterizedtypessinceitispossibleforittogetby—howeverawkwardly—usingthesinglyrootedhierarchy.However,acurrentproposalforparameterizedtypesusesasyntaxthatisstrikinglysimilartoC++templat(yī)es.對象的創(chuàng)建和存在時間從技術(shù)角度說,OOP(面向?qū)ο蟪绦蛟O(shè)計)只是涉及抽象的數(shù)據(jù)類型、繼承以及多形性,但另一些問題也也許顯得非常重要。本節(jié)將就這些問題進行探討。最重要的問題之一是對象的創(chuàng)建及破壞方式。對象需要的數(shù)據(jù)位于哪兒,如何控制對象的“存在時間”呢?針對這個問題,解決的方案是各異其趣的。C++認(rèn)為程序的執(zhí)行效率是最重要的一個問題,所以它允許程序員作出選擇。為獲得最快的運營速度,存儲以及存在時間可在編寫程序時決定,只需將對象放置在堆棧(有時也叫作自動或定域變量)或者靜態(tài)存儲區(qū)域即可。這樣便為存儲空間的分派和釋放提供了一個優(yōu)先級。某些情況下,這種優(yōu)先級的控制是非常有價值的。然而,我們同時也犧牲了靈活性,由于在編寫程序時,必須知道對象的準(zhǔn)確的數(shù)量、存在時間、以及類型。假如要解決的是一個較常規(guī)的問題,如計算機輔助設(shè)計、倉儲管理或者空中交通控制,這一方法就顯得太局限了。第二個方法是在一個內(nèi)存池中動態(tài)創(chuàng)建對象,該內(nèi)存池亦叫“堆”或者“內(nèi)存堆”。若采用這種方式,除非進入運營期,否則主線不知道到底需要多少個對象,也不知道它們的存在時間有多長,以及準(zhǔn)確的類型是什么。這些參數(shù)都在程序正式運營時才決定的。若需一個新對象,只需在需要它的時候在內(nèi)存堆里簡樸地創(chuàng)建它即可。由于存儲空間的管理是運營期間動態(tài)進行的,所以在內(nèi)存堆里分派存儲空間的時間比在堆棧里創(chuàng)建的時間長得多(在堆棧里創(chuàng)建存儲空間一般只需要一個簡樸的指令,將堆棧指針向下或向下移動即可)。由于動態(tài)創(chuàng)建方法使對象本來就傾向于復(fù)雜,所以查找存儲空間以及釋放它所需的額外開銷不會為對象的創(chuàng)建導(dǎo)致明顯的影響。除此以外,更大的靈活性對于常規(guī)編程問題的解決是至關(guān)重要的。C++允許我們決定是在寫程序時創(chuàng)建對象,還是在運營期間創(chuàng)建,這種控制方法更加靈活。大家或許認(rèn)為既然它如此靈活,那么無論如何都應(yīng)在內(nèi)存堆里創(chuàng)建對象,而不是在堆棧中創(chuàng)建。但還要考慮此外一個問題,亦即對象的“存在時間”或者“生存時間”(Lifetime)。若在堆?;蛘哽o態(tài)存儲空間里創(chuàng)建一個對象,編譯器會判斷對象的連續(xù)時間有多長,屆時會自動“破壞”或者“清除”它。程序員可用兩種方法來破壞一個對象:用程序化的方式?jīng)Q定何時破壞對象,或者運用由運營環(huán)境提供的一種“垃圾收集器”特性,自動尋找那些不再使用的對象,并將其清除。當(dāng)然,垃圾收集器顯得方便得多,但規(guī)定所有應(yīng)用程序都必須容忍垃圾收集器的存在,并能默許隨垃圾收集帶來的額外開銷。但這并不符合C++語言的設(shè)計宗旨,所以未能涉及到C++里。但Java的確提供了一個垃圾收集器(Smalltalk也有這樣的設(shè)計;盡管Delphi默認(rèn)為沒有垃圾收集器,但可選擇安裝;而C++亦可使用一些由其他公司開發(fā)的垃圾收集產(chǎn)品)。本節(jié)剩下的部分將討論操縱對象時要考慮的另一些因素。1單根結(jié)構(gòu)在面向?qū)ο蟮某绦蛟O(shè)計中,由于C++的引入而顯得尤為突出的一個問題是:所有類最終是否都應(yīng)從單獨一個基礎(chǔ)類繼承。在Java中(與其他幾乎所有OOP語言同樣),對這個問題的答案都是肯定的,并且這個終級基礎(chǔ)類的名字很簡樸,就是一個“Object”。這種“單根結(jié)構(gòu)”具有許多方面的優(yōu)點。單根結(jié)構(gòu)中的所有對象都有一個通用接口,所以它們最終都屬于相同的類型。另一種方案(就象C++那樣)是我們不能保證所有東西都屬于相同的基本類型。從向后兼容的角度看,這一方案可與C模型更好地配合,并且可以認(rèn)為它的限制更少一些。但假期我們想進行純粹的面向?qū)ο缶幊?那么必須構(gòu)建自己的結(jié)構(gòu),以期獲得與內(nèi)建到其他OOP語言里的同樣的便利。需添加我們要用到的各種新類庫,還要使用另一些不兼容的接口。理所當(dāng)然地,這也需要付出額外的精力使新接口與自己的設(shè)計方案配合(也許還需要多重繼承)。為得到C++額外的“靈活性”,付出這樣的代價值得嗎?當(dāng)然,假如真的需要——假如早已是C專家,假如對C有難舍的情結(jié)——那么就真的很值得。但假如你是一名新手,初次接觸這類設(shè)計,象Java那樣的替換方案也許會更省事一些。單根結(jié)構(gòu)中的所有對象(比如所有Java對象)都可以保證擁有一些特定的功能。在自己的系統(tǒng)中,我們知道對每個對象都能進行一些基本操作。一個單根結(jié)構(gòu),加上所有對象都在內(nèi)存堆中創(chuàng)建,可以極大簡化參數(shù)的傳遞(這在C++里是一個復(fù)雜的概念)。運用單根結(jié)構(gòu),我們可以更方便地實現(xiàn)一個垃圾收集器。與此有關(guān)的必要支持可安裝于基礎(chǔ)類中,而垃圾收集器可將適當(dāng)?shù)南l(fā)給系統(tǒng)內(nèi)的任何對象。假如沒有這種單根結(jié)構(gòu),并且系統(tǒng)通過一個句柄來操縱對象,那么實現(xiàn)垃圾收集器的途徑會有很大的不同,并且會面臨許多障礙。由于運營期的類型信息肯定存在于所有對象中,所以永遠(yuǎn)不會碰到判斷不出一個對象的類型的情況。這對系統(tǒng)級的操
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 高碑店假山的施工方案
- 碎石加工施工方案
- 總包與勞務(wù)分包消防協(xié)議
- 基坑爬梯施工方案
- 逆變一體機基礎(chǔ)施工方案
- 佛山歐式花園施工方案
- 上海倍發(fā)信息科技有限公司股東全部權(quán)益價值資產(chǎn)評估報告
- 建元信托2024年度審計報告及財務(wù)報表
- 浙江紡織電纜托架施工方案
- 澄海區(qū)中學(xué)初二數(shù)學(xué)試卷
- 臨時工雇傭合同范本2025年度
- (二調(diào))武漢市2025屆高中畢業(yè)生二月調(diào)研考試 地理試卷
- “艾梅乙”感染者消除醫(yī)療歧視制度-
- 2024-2025學(xué)年八年級地理下冊第七章《南方地區(qū)》檢測卷(人教版)
- 森林防火知識
- 2025年黑龍江林業(yè)職業(yè)技術(shù)學(xué)院單招職業(yè)適應(yīng)性測試題庫帶答案
- 2025-2030年中國測序儀市場運行態(tài)勢及發(fā)展規(guī)劃分析報告
- 第二單元第1課《精彩瞬間》第2課時 課件-七年級美術(shù)下冊(人教版2024)
- 《物理前沿科學(xué)》課件
- 2025年公共營養(yǎng)師三級理論試題及答案
- 餐廳市場調(diào)研與定位
評論
0/150
提交評論