版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(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,whichshouldsatisfymostnee(cuò)ds.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-timee(cuò)rrorcalledanexception,whichwillbedescribedshortly.Whenyoufetchobjectreferencesfromacontainer,though,youmusthavesomewaytorememberexactlywhattheyaresoyoucanperformaproperdowncast.Downcastingandtherun-timechecksrequiree(cuò)xtratimefortherunningprogram,andextraeffortfromtheprogrammer.Wouldn’titmakesensetosomehowcreatethecontainersothatitknowsthetypesthatitholds,eliminatingthenee(cuò)dforthedowncastandapossiblemistake?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í)間從技術(shù)角度說,OOP(面向?qū)ο蟪绦蛟O(shè)計(jì))只是涉及抽象的數(shù)據(jù)類型、繼承以及多形性,但另一些問題也也許顯得非常重要。本節(jié)將就這些問題進(jìn)行探討。最重要的問題之一是對象的創(chuàng)建及破壞方式。對象需要的數(shù)據(jù)位于哪兒,如何控制對象的“存在時(shí)間”呢?針對這個(gè)問題,解決的方案是各異其趣的。C++認(rèn)為程序的執(zhí)行效率是最重要的一個(gè)問題,所以它允許程序員作出選擇。為獲得最快的運(yùn)營速度,存儲(chǔ)以及存在時(shí)間可在編寫程序時(shí)決定,只需將對象放置在堆棧(有時(shí)也叫作自動(dòng)或定域變量)或者靜態(tài)存儲(chǔ)區(qū)域即可。這樣便為存儲(chǔ)空間的分派和釋放提供了一個(gè)優(yōu)先級。某些情況下,這種優(yōu)先級的控制是非常有價(jià)值的。然而,我們同時(shí)也犧牲了靈活性,由于在編寫程序時(shí),必須知道對象的準(zhǔn)確的數(shù)量、存在時(shí)間、以及類型。假如要解決的是一個(gè)較常規(guī)的問題,如計(jì)算機(jī)輔助設(shè)計(jì)、倉儲(chǔ)管理或者空中交通控制,這一方法就顯得太局限了。第二個(gè)方法是在一個(gè)內(nèi)存池中動(dòng)態(tài)創(chuàng)建對象,該內(nèi)存池亦叫“堆”或者“內(nèi)存堆”。若采用這種方式,除非進(jìn)入運(yùn)營期,否則主線不知道到底需要多少個(gè)對象,也不知道它們的存在時(shí)間有多長,以及準(zhǔn)確的類型是什么。這些參數(shù)都在程序正式運(yùn)營時(shí)才決定的。若需一個(gè)新對象,只需在需要它的時(shí)候在內(nèi)存堆里簡樸地創(chuàng)建它即可。由于存儲(chǔ)空間的管理是運(yùn)營期間動(dòng)態(tài)進(jìn)行的,所以在內(nèi)存堆里分派存儲(chǔ)空間的時(shí)間比在堆棧里創(chuàng)建的時(shí)間長得多(在堆棧里創(chuàng)建存儲(chǔ)空間一般只需要一個(gè)簡樸的指令,將堆棧指針向下或向下移動(dòng)即可)。由于動(dòng)態(tài)創(chuàng)建方法使對象本來就傾向于復(fù)雜,所以查找存儲(chǔ)空間以及釋放它所需的額外開銷不會(huì)為對象的創(chuàng)建導(dǎo)致明顯的影響。除此以外,更大的靈活性對于常規(guī)編程問題的解決是至關(guān)重要的。C++允許我們決定是在寫程序時(shí)創(chuàng)建對象,還是在運(yùn)營期間創(chuàng)建,這種控制方法更加靈活。大家或許認(rèn)為既然它如此靈活,那么無論如何都應(yīng)在內(nèi)存堆里創(chuàng)建對象,而不是在堆棧中創(chuàng)建。但還要考慮此外一個(gè)問題,亦即對象的“存在時(shí)間”或者“生存時(shí)間”(Lifetime)。若在堆?;蛘哽o態(tài)存儲(chǔ)空間里創(chuàng)建一個(gè)對象,編譯器會(huì)判斷對象的連續(xù)時(shí)間有多長,屆時(shí)會(huì)自動(dòng)“破壞”或者“清除”它。程序員可用兩種方法來破壞一個(gè)對象:用程序化的方式?jīng)Q定何時(shí)破壞對象,或者運(yùn)用由運(yùn)營環(huán)境提供的一種“垃圾收集器”特性,自動(dòng)尋找那些不再使用的對象,并將其清除。當(dāng)然,垃圾收集器顯得方便得多,但規(guī)定所有應(yīng)用程序都必須容忍垃圾收集器的存在,并能默許隨垃圾收集帶來的額外開銷。但這并不符合C++語言的設(shè)計(jì)宗旨,所以未能涉及到C++里。但Java的確提供了一個(gè)垃圾收集器(Smalltalk也有這樣的設(shè)計(jì);盡管Delphi默認(rèn)為沒有垃圾收集器,但可選擇安裝;而C++亦可使用一些由其他公司開發(fā)的垃圾收集產(chǎn)品)。本節(jié)剩下的部分將討論操縱對象時(shí)要考慮的另一些因素。1單根結(jié)構(gòu)在面向?qū)ο蟮某绦蛟O(shè)計(jì)中,由于C++的引入而顯得尤為突出的一個(gè)問題是:所有類最終是否都應(yīng)從單獨(dú)一個(gè)基礎(chǔ)類繼承。在Java中(與其他幾乎所有OOP語言同樣),對這個(gè)問題的答案都是肯定的,并且這個(gè)終級基礎(chǔ)類的名字很簡樸,就是一個(gè)“Object”。這種“單根結(jié)構(gòu)”具有許多方面的優(yōu)點(diǎn)。單根結(jié)構(gòu)中的所有對象都有一個(gè)通用接口,所以它們最終都屬于相同的類型。另一種方案(就象C++那樣)是我們不能保證所有東西都屬于相同的基本類型。從向后兼容的角度看,這一方案可與C模型更好地配合,并且可以認(rèn)為它的限制更少一些。但假期我們想進(jìn)行純粹的面向?qū)ο缶幊?那么必須構(gòu)建自己的結(jié)構(gòu),以期獲得與內(nèi)建到其他OOP語言里的同樣的便利。需添加我們要用到的各種新類庫,還要使用另一些不兼容的接口。理所當(dāng)然地,這也需要付出額外的精力使新接口與自己的設(shè)計(jì)方案配合(也許還需要多重繼承)。為得到C++額外的“靈活性”,付出這樣的代價(jià)值得嗎?當(dāng)然,假如真的需要——假如早已是C專家,假如對C有難舍的情結(jié)——那么就真的很值得。但假如你是一名新手,初次接觸這類設(shè)計(jì),象Java那樣的替換方案也許會(huì)更省事一些。單根結(jié)構(gòu)中的所有對象(比如所有Java對象)都可以保證擁有一些特定的功能。在自己的系統(tǒng)中,我們知道對每個(gè)對象都能進(jìn)行一些基本操作。一個(gè)單根結(jié)構(gòu),加上所有對象都在內(nèi)存堆中創(chuàng)建,可以極大簡化參數(shù)的傳遞(這在C++里是一個(gè)復(fù)雜的概念)。運(yùn)用單根結(jié)構(gòu),我們可以更方便地實(shí)現(xiàn)一個(gè)垃圾收集器。與此有關(guān)的必要支持可安裝于基礎(chǔ)類中,而垃圾收集器可將適當(dāng)?shù)南l(fā)給系統(tǒng)內(nèi)的任何對象。假如沒有這種單根結(jié)構(gòu),并且系統(tǒng)通過一個(gè)句柄來操縱對象,那么實(shí)現(xiàn)垃圾收集器的途徑會(huì)有很大的不同,并且會(huì)面臨許多障礙。由于運(yùn)營期的類型信息肯定存在于所有對象中,所以永遠(yuǎn)不會(huì)碰到判斷不出一個(gè)對象的類型的情況。這對系統(tǒng)級的操
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 云隊(duì)課的心得體會(huì)
- 高中寒假實(shí)踐報(bào)告
- 社團(tuán)活動(dòng)策劃案范文8篇
- 西湖導(dǎo)游詞范文300字(33篇)
- 銀行公司業(yè)務(wù)工作總結(jié)(7篇)
- DB12-T 1108-2021 車用乙醇汽油(E10)快速篩查技術(shù)規(guī)范
- DB11T 1665-2019 超低能耗居住建筑設(shè)計(jì)標(biāo)準(zhǔn)
- 化工熱力學(xué)教案
- 2023年電子計(jì)步器實(shí)驗(yàn)分析儀器資金籌措計(jì)劃書
- 二年級數(shù)學(xué)計(jì)算題專項(xiàng)練習(xí)1000題匯編集錦
- 遠(yuǎn)離黃賭毒學(xué)習(xí)教案
- 影響健康因素多 課件 2024-2025學(xué)年人教版(2024)初中體育與健康七年級全一冊
- 幼兒園轉(zhuǎn)課協(xié)議書范文范本
- 安徽省2023-2024學(xué)年高一上學(xué)期期中考試物理試題(含答案)
- 一年級上冊勞動(dòng)《各種各樣的職業(yè)》課件
- 班主任能力大賽情景答辯環(huán)節(jié)真題及答案高中組
- 知道智慧網(wǎng)課《科技倫理》章節(jié)測試答案
- 國家開放大學(xué)《中文學(xué)科論文寫作》形考任務(wù)1-4參考答案
- 大學(xué)生職業(yè)生涯發(fā)展展示
- 2024年納稅服務(wù)條線專業(yè)知識(shí)考試題庫(含答案)
- 高考英語高頻短語按字母排序
評論
0/150
提交評論