




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、關(guān)鍵字 關(guān)鍵字 auto 關(guān)鍵字,現(xiàn)在有例如推斷數(shù)據(jù)類型從表達(dá)式或 auto 變量而來對于編譯時間的斷言。對模板和有效性不能使用宏#ifdefLambda 表達(dá)式 邏輯定義的函數(shù)。從函數(shù)指針和類對象中繼承 Trailing 返回類型 但模板的返回類型不能夠表達(dá)式,是很有用的 C+ 語言的特性一定被包含在VC8 和VC9 (+ . 被整理到C+0 x中介碼名字已經(jīng)改為C+0 x, 許多編譯器都已經(jīng)介紹了它的一些特性。這個指南將嘗試給你介紹 C+ 語言的新特性。請注意,盡管這些特性已經(jīng)應(yīng)用到其他的編譯器上,但我只在 Visual C+ 2010 編譯器上解釋一些新的特性。在其他編譯器上C+的新特性
2、以下列表是我將要 的 C+ 語言增加的一些新特性。我已經(jīng) 的強(qiáng)調(diào)了lambdas 和 R-values這兩個新名詞暫時沒有合適的漢語翻譯)了,由于我還沒有在哪里找到任何可消化的現(xiàn)在,編譯器就不知道變量nResult 的類型,使用auto關(guān)鍵字*,由于nVariablenVariable3autonVariable5=/被推論的 double, 因為 sqrt 接受 3 不同的數(shù)據(jù)類型,但傳入double,覆蓋返回值/ autonVariable=/錯誤,因為 sqrt的調(diào)用的/ 這個錯誤與 auto 關(guān)鍵字不相關(guān)autonVariable15654autonVariable21003; aut
3、onVariable3 1003.0double類型的推論由于編譯器把整個表達(dá)式作 它將產(chǎn)生一個錯誤。這不像是Visual Basic 或web幾個例子autonVariable/Compiler/errorC3531:nVariable:asymbolwhosetypeautoveannVariable=autonVariable=structautoVariable=/ error C2864: AutoStruct:Variable : 只有靜態(tài)只讀的成員變量才可在結(jié)構(gòu)體或類中structautoVariable=/ error C2864: AutoStruct:Variable :
4、只有靜態(tài)只讀的成員變量才可在結(jié)構(gòu)體或類中如果你需要一個 auto的返回類型或auto 你不能在 類class或結(jié)構(gòu)體struct中使用autoautovoidArgumentDeduction(auto/ C3533: auto: 參數(shù)類型的變量不能夠包含不允許的情景autoauto/ error C3532: 數(shù)組類型的的元素的類型不能定義為包含 constautoPI=3.14; /volatileautoIsFinished=false; /constautonStringLen=constvolatile修飾符autoiArray=10;new操作符auto&pVariable=nVa
5、riable1; /是的,又該這個變量的值,將修改的變量autopVariable=&pVariable6;auto*pVariable7=&nVariable1;位很確定的事情你可以使用 size_t代 或 64 std:vectorStrings;/string位很確定的事情你可以使用 size_t代 或 64 std:vectorStrings;/string/Pushseveral2autonLength=strlen(Theauto nLength=strlen(Theauto翼翼。 如果你不幸,只有一個變量使用了auto產(chǎn)生C3538的錯誤(如上)因此什么時候應(yīng)該真正的使用 aut
6、o關(guān)鍵字呢 ForautonVariable= float ,但實(shí)際上為double。autonVariable=sqrt(100.0),nVariableX=autoa=10,b=10.30,errorC3538:在一個declarator-list,string,string,string:const_iteratorm_iter=/ cbegin使用的情況下,迭代器總是只讀的for(autoiter=Strings.cbegin();iter!=Strings.cend();+iter)的對象上調(diào)用 begin方法時, 你不能夠再將它分到一個非只讀的iterator 上, 一樣, 因為我
7、不是在寫STL, 請自己閱讀并做相關(guān)實(shí)驗)概括了所有的復(fù)雜性,并且引進(jìn)了autoC+STL cbegin, cend, crbegincrend方法提供了便利。C 前綴意思為只讀。他們總是返回 const_iterator的迭代器,不管對象(容器)是否為const。老的方法依靠對象的常量/meusingfor(vector:const_iterator iter = Strings.begin();iter!=Strings.end();+iter)std:cout*iterstd:endl;會傾向于使用const_iterator來代替iteratorfor(autoiter=Strings
8、.begin();iter!=Strings.end();std:cout*iterstd:endl; 笨拙的。盡管可以選擇使用關(guān)鍵字typedef在程序的某些地方來返回類型并且使用類型名。但是對于迭代器類型又有多少呢? 并且一個迭代器類型只用一次又會怎樣呢?如此顯示出它for(std:vector:iterator iter = Strings.begin();iter!=Strings.end(); +iter) std:cout*iterstd:endl;autokeyword(typededuction)-decltype(nVariable1)翻譯成 類型。decltype關(guān)鍵字與t
9、ypeid關(guān)鍵autokeyword(typededuction)-decltype(nVariable1)翻譯成 類型。decltype關(guān)鍵字與typeid關(guān)鍵字不同。 autoxVariable=typeid(nVariable1)nVariable2為一 decltype(nVariable1) decltype 關(guān)鍵為變量分配一個 Lambdas(以下文章是關(guān)于lambdas的解釋。為返回類型指定一個 盡管不涉及表達(dá)式語法是必須的。我將程式后它外部autom_iter=外部參考decltype decltype(1/0) Infinite; / 0的情況,編譯器并不產(chǎn)/程序不會 exi
10、t, 會保存 exit(0), 的類型/在不進(jìn)行函數(shù)調(diào)用的情況下指定exit 會使得MyExitFunction 的返回類型有所不decltype(exit(0)使用auto從右邊的表達(dá)式上推論出類型,的去推論類型。使用 decltype,你不需要指定變量,僅僅 在上面的第二個例子中,mstr 是std:map 對象, 取回迭代器,即為 map 元素的第二個成員,并最終為它的分配器類型。因此,為string 推斷出 std:allocator 類型(請看上面,mstr被 )。decltype(Strings.begin() string_iterator; decltype(xVariable
11、)decltype(SomeFunc) yVar; 假設(shè)xVariable(實(shí)際上,為SomeFunction的返回類型)的類型是現(xiàn)在,你不能再次nullptr 關(guān)鍵字-(使用/clr 選項編譯器要求是錯誤的.nullptr 關(guān)鍵字-(使用/clr 選項編譯器要求是錯誤的.MSDN 沒有更新, 寫這篇文章之時Externalvoidvoidfx(nullptr);/調(diào)用 /調(diào)用 請記住,nullptr是一個關(guān)鍵字,不是類型。因此,對于它你不能使用操作符sizeof或 ,NULL宏和關(guān)鍵字nullptr是不同的兩個實(shí)體。NULL就是0,其例如void*pBuffer=if(pBuffer=nul
12、lptr /Dosomethingwithnull-ercase/Withvoidif(this !=.關(guān)鍵字是要知道,關(guān)鍵字不但用于本地 C+, 而且應(yīng)用于托管的代碼中。如果你以混合的模式使用 C+, 你可以顯式的的使用關(guān)鍵字 nullptr來陳述本地空指針,并且使用nullptr表示托管空指針。即使在混合的模式下編程,你不會常使用 nullptr。error C2466:不能夠分配固定大小為0 的數(shù)外部ic_assert 關(guān)鍵字-(Lambda)表達(dá)式由于任何一個指針類型的大小是相同的,當(dāng)選擇目標(biāo) 做編譯時。在早期的編譯器中, 需要使用_S IC_ASSERT,盡管它不會做任何事情,但是
13、了數(shù)組的大小狀況。因此,如果條件為真,它將 大小為 1error C2466:不能夠分配固定大小為0 的數(shù)外部ic_assert 關(guān)鍵字-(Lambda)表達(dá)式由于任何一個指針類型的大小是相同的,當(dāng)選擇目標(biāo) 做編譯時。在早期的編譯器中, 需要使用_S IC_ASSERT,盡管它不會做任何事情,但是 了數(shù)組的大小狀況。因此,如果條件為真,它將 大小為 1的數(shù)組;如果條件為假它將 大小為 0 的數(shù)組這將導(dǎo)致編譯器產(chǎn)生一個錯誤。錯誤通常不是友好的。ic_assert(sizeof(void*)=Thiscodeshouldonlybecompiledas32-errorC2338:Nineisnot
14、equaltoic_assert(10=9,Nineisnotequalto器會產(chǎn)生一個C2338 的錯誤提示。例如:ic_assert(,ic_assert 關(guān)鍵使用則了嗎到一個局部變量pi中通常, 你). pi=return3.14159;(); std:cout pi;了嗎到一個局部變量pi中通常, 你). pi=return3.14159;(); std:cout n2)?(n1): (56,nMin= return(n1doublereturn3.14159;Q. 關(guān)于返回值是什呢生錯誤生錯誤class TestClass函數(shù)不止一個返回表達(dá)式會是什么情況呢-doublereturn
15、3.14159;(); /()-autopi=returnautonSum= returnn1+n2+n3;autoxVal=(floatx)-float t; return ()-floaterrorC2090:()-autoerrorC3558*:const_iterator& x)-decltype(x);/Deducingtype of否把一個函需要做一些事情,如顯示一個值,執(zhí)行別的一些指令將會是怎樣的呢?我能到一個已經(jīng)定義的函數(shù)中,并在一些地方再次使用一函數(shù)被定義成一個局部函數(shù),能否穿越函數(shù)作用域來使用呢?讓函if否把一個函需要做一些事情,如顯示一個值,執(zhí)行別的一些指令將會是怎樣的呢
16、?我能到一個已經(jīng)定義的函數(shù)中,并在一些地方再次使用一函數(shù)被定義成一個局部函數(shù),能否穿越函數(shù)作用域來使用呢?讓函if(!IsEven(45)std:coutif(n%2 = 0) returnTestClass test; ptr=n1)-*p=*p = n1; delete usingautoDisplayIfEven=n)-if(n%2=std:coutif(n%2=std:coutNumberisevenn; std:coutif(n%2=0)returntrue; else return false;void/調(diào)用它IsEven你會明白以下4條是繼承至C+的優(yōu)點(diǎn)private變量,你無,
17、 得命名空間的解決方案。因此std命名空間的范圍對于DisplayIfEven是不可用的。一函數(shù)能否包含另外一函數(shù)或常規(guī)函數(shù)嗎函數(shù)支持缺省參數(shù)嗎coutCallinglambda.; /使用&你指定了所有的變量通auto/使用&你指定了所有的變量通autoResetAll=&()-/由于你是通a=b=c= 例 return(a+b+c)/ 不能修改任何變量的float x=例 a=10,b=20,std:cout Valueofa= a std:endl;不能夠修aerrorC3491:aa是通過值來/不std:coutb/errorC3493:b不能夠被隱式的捕因為沒有缺省的捕獲例 & 通v
18、ar var&var 通來捕獲var。, 例 &,b;/(1)通。, 例 &,b;/(1)通b,c,&nSum; / (3通過值來捕獲nSum為值捕獲a4)所有通過值捕獲,隱藏了 a因為 a現(xiàn)在是一個函數(shù)的參數(shù),糟/ &或=必須首先出現(xiàn)(如果被指定a,b,c,& / 邏輯上與上述相似,但是出錯的指定之前, 將 錯誤:/ 只有nSum是通=,nSum=如例4 所示,出第二個例子, 而所有的三個參數(shù)(a, b, c)的和被在nSum中。例 /通過值僅捕獲a和 nSum=a,b/你還記得()對于無參數(shù)returnstd:coutSum:void / ()是必須的,指定一個 mutable關(guān)鍵字因為所
19、有變量都是在通過值調(diào)用的模式下捕編譯器會產(chǎn)生y,z均未使/ x的值依然為到現(xiàn)在, 已經(jīng)看到了 可以防止一些變量 獲,防止通過值的關(guān)鍵字為 const,防止通過 的關(guān)鍵字 non-const。因此,在上面的捕獲類別中 已經(jīng)覆蓋了 1,2 4。捕constreference是不可能的(即,const&a)。 現(xiàn)在將會去研究一下最后一mutable 在參數(shù)說明括號后面, 指定了一個mutable關(guān)鍵字。 把所有通過值來捕獲的變量放入一個通過值調(diào)用模式。如果 不放置一個mutable關(guān)鍵字,所有通過值來捕獲的變量都是只讀的,你不能在 函數(shù)中修改它。放置一個關(guān)鍵字 mutable就告訴編譯器強(qiáng)制拷貝所的
20、通過值來捕獲const 或非const 變量。 或者簡單點(diǎn),你可以假定他們通過傳參的形式傳入例如&,var除過var是通過值捕獲的,其他均通=,&var-除過var是通var1var2 通過值來捕獲變量var1var2 &var1,&var2 通來var1,var2var1,&var2 通過值來捕獲var1來捕獲var2&,a,c,nSum(2)b,&a&c&nSum(1相&無效&nSum,無效a,b,c,&無效tr1命名空間在技術(shù) 1 中,技術(shù) 1 被C+0 x 息。bool(tr1命名空間在技術(shù) 1 中,技術(shù) 1 被C+0 x 息。不能夠在函數(shù)參數(shù)中使用/ 調(diào)用它在程序的某些地方用auto
21、關(guān)鍵字會更加的方便。這里有一些用例,然而,你在哪里必須使用一個function表達(dá)式時. 如下例:)sIsEven=n)-boolreturnn%2=函數(shù)與函數(shù)指針,函數(shù)對象有怎樣的區(qū)別呢?函數(shù)的指針不保留狀態(tài),而 函數(shù)保留。通過 的捕獲, 函數(shù)可以在調(diào)用期間保留它們 須嚴(yán)格遵守調(diào)用重載操作符()。更重要的是,你必須在函數(shù)塊外面做這些工作以便于其他對于這個類應(yīng)該調(diào)用 表達(dá)式的類型是什么呢表達(dá)式其實(shí)就是一些類。 你能夠把它們在一個function類對象中。這個類,對于表達(dá)式,被定義在 std:tr1 命名空間中。讓函voidstd:cout(n%2=函voidstd:cout(n%2=0)?Ye
22、s:/類對操作符classvoidstd:cout/調(diào)用指定的函數(shù)在 C+中介紹 表達(dá)式的目的是什么表達(dá)式對于許多STL 函數(shù)時非常有用的即函數(shù)要求一個函數(shù)指針或函數(shù)對象(使用 初,我沒去覆蓋STL 的函數(shù),但是以一種簡單的容易理解的形式解釋了STL 的例子也許顯得很多余,但卻能夠幫助澄清這個者 表達(dá)式應(yīng)該是需要的類型,返回一個 void類型并且接受一個 類型的參數(shù)作為唯一,不應(yīng)當(dāng)拷貝函數(shù)voidTakeLambda(function&/只讀voidTakeLambda(constfunction&完全限定voidTakeLambda(conststd:tr1:function&好! /傳進(jìn)一
23、個函數(shù)對class好! /傳進(jìn)一個函數(shù)對classnPredicate):Predicate(nPredicate)voidif(n std:cout LessnPredicate; std:coutnstd:coutn/ 傳遞一個函數(shù)指 傳遞一個函數(shù)對 /另式Callback obj; CallbackSomething(44,obj);/本地定義表達(dá)式CallbackSomething(59,std:coutHalf:因此,如果你把一個 obj對象傳進(jìn)多個CallbackSomething的調(diào)用(或者任何其他相似 的函數(shù)),它將擁有相同的斷言(狀態(tài))。 就像你所了解的那樣,這在函數(shù)指針中絕
24、對是不可能 使名表達(dá)式, autoeful = n)/通來捕獲變量就 OK。當(dāng)改n1000”Predicate=在有狀態(tài)的變量autoeful = if(nstd:cout LessnPredicate; std:coutnCallbackSomething(59,eful);/n CallbackSomething(100,eful); /PredicateNOTchangedfor / 24 CallBack 構(gòu)造函數(shù)的CallbackSomething!的參/式 就像我解釋的怎樣利用for_each函數(shù)來使用 表達(dá)式一樣,你可以使用其他就像我解釋的怎樣利用for_each函數(shù)來使用 表達(dá)
25、式一樣,你可以使用其他transform,generate,remove_if等等來使用它。 表達(dá)式不僅僅局限于使用STL 功能。他們也能夠被很有效率的適用于任何你所需求的函數(shù)對象。你需要確保給他傳遞/n被通傳遞(與通捕獲不相同for_each(Array,Array+10,&n)n*= 4;第一個調(diào)用調(diào)用IsEven函數(shù),第二個調(diào)用調(diào)用 表達(dá)式,此表達(dá)式在for_each函數(shù)中 這是一個非常簡單的例子,for_each和 表達(dá)式不需要寫一個函數(shù)或類的情況下就可以被利用來能顯示值。 值得肯定, 表達(dá)式能被進(jìn)一步擴(kuò)展用來做額外的工作如打印是個數(shù)是否為素數(shù),或者計算求和(通過使用 調(diào)用),或修改一
26、個范圍的元素。修改 表達(dá)式的形參對,是的,你能做到它,我一直在 通過 來捕獲并做出修改,但是沒有涵蓋修改自身的參數(shù)。這個需求一直都沒有出現(xiàn)直到現(xiàn)在。為了這樣做,僅通過 (或指針)接受 表達(dá)式的Well, yes! You can dot. For long, I talked about taking captures by referen and making modifications, but did not cover modifying the argument itself. The needdidnotarisetillnow.Todothis,justtakethelambda
27、sparameterbyreference(orusingArray10=for_each(Array,&Array10,for_each(Array,Array+10,n)std:cout nVC+ 的博客,如下使用 STL 為什么? CalculateSum(10,20,為什么? CalculateSum(10,20,n)std:coutsumis:n;/C2664:CalculateSum:cannotconvertparameter3 voidstd:coutSumis:returnautoGetPI()-returnIt returns a long, asyou can see.
28、It uses the newsyntaxof specifying a return type, the actual type is specified after the -operator. One more exautoGetCPUSpeedInHertz()-return同理,其他的STL 函數(shù),如,等等,可以工作在三種情況下:函數(shù)指針,函數(shù)對象,API函數(shù)中使用 表達(dá)式,如SetTimerEnumFontFami s,等等別再計劃了!即使強(qiáng)制類型轉(zhuǎn)換 表達(dá)式(通過傳遞它的地址),也不會工作,程序會在運(yùn)行時 。TrailingreturnLets start wisimpleexl
29、e.Followingisafunctionwhosereturntypeislong. This is not a lambda, but a function.templatedecltype(t1+returnt1+AddThem(10.0,AddThem(C+, X); template SecondType AddThem(Type t1, SecondType t2);templateType,typename/*UnknonwnReturnType*/ Typet1,SecondTypereturnt1+decltypekeywordabove,torecollect.Forbo
30、thofthefunctionsgivenabove,you obviously need not use this feature!Wheretoactuallyuse Considerthetemplatefunctionwithsomeypes.t,thecompilerwontbotherKindlyignorefunctionwithsomeypes.t,thecompilerwontbotherKindlyignorethemissingcopyconstructor,weareusingthedefaultconstructor.Forunderstanding,methecop
31、yconstructor(oravoidSetSimple(constSimple&/CreateaSimpleobjectfromSimpleobject/UseHere,youcanttheGetSimplemethodreturnsaSimpleobject.SetSimpletakesaSimpleobjectbyreference.InacalltoSetSimple,weassoonasSetSimplereturns.LetsextendclassSimpleSimplereturnvoidSetSimple(const SetSimple(GetSimple()anything
32、(samerulesaswithnormaltemplateR-Value Ia me tyouknowwhatcall-by-value,byreference,andbyconstantreference mean.Ifurthera me tyouknowwh -valueand R-valuemean. Now,lets take an ex le where R-value referen would make sense:overloaded+operatorwouldbethereturntype.Iftypesarenotnative,andoverloadcouldbefou
33、nd,thecompilerwouldraiseanerror.Itisimportanttotthetypedeductionwillonlytakeplacewhenyouinstantiatethe sup edtodestroy100bytes.Dont sup edtodestroy100bytes.Dontgettheprobleminhere?Okay,letmeexplain. Twoobjectsarebeingcreated(oneinGetSimple,oneinSetSimple),andboth are allocating 100 bytes of memory.
34、Right? This is like copying a file/folder to anotherlocation.Butasyoucanseefromtheex lecode,onlyobjectis bytes allocated by rsof therewasnosimpleway,unlesswewroteourownmemory/objectroutines(liketheCStringclassdoes).InC+0 x,wecant. inshort,welloptimizetheroutinethistheproblemandsolutionisheformofRVOa
35、ndNRVO(Named meaningful.Forthis,weuseanewroduced:R-valueTheabovecodeisformovingthecontentfromtheoldobjecttothenewThisisverysimilartomovingafile/folder.NotetthesbeenvoidSetSimple(Simple&rSimple)/R-ValueNON-CONST/Performingmemoryassignmenthere,forSimpleobject.Memory=rSimple.Memory; rSimple.Memory = nu
36、llptr;/UsedeleteDeclarator:&.Basicsyntax:Type&identifier.NowwemodifytheabovestepbyBythis,wesave100bytes!Notabigamount,though.Butifthisfeatureisused objectiscreated,anditallocatesItisabouttobeBefore it gets destroyed, we attach the memory of theobjecttothe second object.Wedetachthememoryfromobject(li
37、ke,settingtheerWeusethesecondThesecondobjectgetsdestroyed,whicheventuallyde-allocatesthe memory originally allocated by the has a memory-poer(say,void*)namedMemory has a memory-poer(say,void*)namedMemory.Thedefaultconstructorsetsit as null. This member is made public for simplifying the topic.Whatif
38、youmakeacalllikeItwouldresultinanerrorsincethecompilercannotconvertSimpletoSimple&. Thevariablexisnottemporary,andcannotbehavelikeanR-valuereference.For this, we may provide an overloaded SetSimplefunction t takes Simple, Simple&, or constSimple&. Thus, you know by nowttemporaryobjectsare actually R
39、-value referen. With R-values, you achieve what is known as move moves,weneedtoprovideamoveconstructor,andoptionallyaThemove-constructorwouldbeverysimilar-justone Simple(constassignmentoperator(operator=),totheThemove Lets implement moving the object withheclassitselfwiththehelpofamove constructor.
40、As you know, a copy constructor would have a signature like:s.MovesenablesyoutowritecodettransfersSimple x; classvoid*Simple()Memory=nullptr;nBytes)Memory=newcharnBytes;SimpleSimplereturnsincewealsoneedtoreset(detach)thememoryoriginallyallocatedby But asyoucan see,themove-constructorisnon-const. Lik
41、e acopy constructorBut asyoucan see,themove-constructorisnon-const. Like acopy constructor takeconst;nothingpreventsthis-ngsoforfeitsthewholee wheretheso-calledmove-constructormaybeNow,methemove-constructorishatcase,thecompiler HereistheupdatedSimpleclassclass/Thevoid*Simple()Memory=nullptr;/TheMOVE
42、-Simple(Simple&/TakeMemory=/Unlikethecopy-constructor,thecompilerdoesnotprovideamove-constructor;youmustwriteittheobjectisbeingmoved(ownershiptransfer),anditwouldcall Why?TheobjectsObjhasbeencreatedonthestack.Thereturntypeiswhichwouldmeanthecopy-constructor(ifprovided;otherwise,therovided)would beca
43、lled. Further,thedestructor for sObjwould beSimplereturn sObj;writing a move-constructor. Why?If you understoodcorrectly, we are detachingresourceownershipfromtheoriginalsource(theargumentofHereisppenswhenyoucalltheGetSimpleHereisppenswhenyoucalltheGetSimpleItisimportanttonote,andunderstandcalled(de
44、faultoruser-Returning an object by value (i.e., Simple, not Simple&or Simple*) causes the copy-constructor or move-constructor to be called. This povery important to understand!Move-constructor detaches the object knowing what the destructor is his case, we are setting Memoryto null, sotDTOR doesnt
45、delete it.1. TheprogramcontrolenterstheGetSimplefunction,allocatesaSimpleobjectonCallsthe(creation)constructorofclassTheconstructorallocatesthedesirednumberofbytes(theThe return sementisreadytoconvertthestackobject sObjtoa returnable object.Here, the smart compiler findst the object iuallybeingmoved
46、;and t the move-constructor is available, it calls the MC.The move constructor (Simple(Simple&) now takes the Memorycontent (insteadofallocatingagain,asthecopy-constructorwouldhavedone).Then itsetstheoriginalobjectsMemorytobenull.Itdoesnotallocateandcopy the memory!Control comes back to return-po.No
47、wtheoriginalsObjistobe -doessObj.Memory=Memory=newif(Memory!=nullptr) delete Memory;Wetwemovedtheoriginalo thenewobject.Thisway,wememoryandsingWetwemovedtheoriginalo thenewobject.Thisway,wememoryandsingtime.Asmentionedr,thissavingisnegligent -Thesignatureoftheuser-definedoperatorcanWhatabouttheement
48、:obj3=GetSimple()?TheobjectreturnedGetSimpleistemporary, asyou should clearly knowby now.Thus, wecan(and classAndhereisthemodifiedSimpleclass(previouscodeomittedforbrevity).assignmentisnottakencarevoidoperator=(Simple&);/Modifiesthesource,sinceitis/voidreturnisputforvoidoperator=(constSimple&);/Does
49、ntmodifyThecompilerdoesnotprovidethedefaultmoveassignment-unlikethedefault(copy)assignmentAsyouknow,obj2=obj1wouldcalltheassignment-operator,thereisdontprovideanassignmentoperator,thecompilerwouldprovidetheassignmentoperator(andwouldcopybyte-by-byte).TheobjectontherightremainsSimple obj1(40); Simple
50、obj2,obj3;obj2=obj3=whenitisemployedinlargerdatastructures,and/orwhentemporary-objectscreatedanddestroyedalot,thesavingisThemoveassignment-Checkingifapo erisnull(Memory!=nullptr)isnotrequiredasperC+ standards,butismentionedforclarity.Onyourclasses,youmustdesignMC and DTORso t they have a similar pro
51、tocol.hecaseoftheobj3=GetSimple()ement,thehecaseoftheobj3=GetSimple()ement,thefollowingthingsTheGetSimplefunctionisbeingcalled,whichreturnsatemporaryNow, the spelfunction,moveassignment-operator,istobecalled.Since the compiler identifiest the argument to this spel-function is temporary, it calls the
52、 assignment-operator which takes the R-value reference. This case is the same as the SetSimplementioned above.Themove-assignment-operatortakestheownership,anddetachesthe ownership from the so-called temporary object/R-value reference.The destructor of the temporary-object gets called, which identifi
53、estthe object doesnt own any resource - it does nothing.voidoperator=(constSimple&/De-allocatedelete/Allocaterequiredamountof/andcopy/Thenewandmemcpycallsnot/forbrevity.Another/classisalsorequiredtoholdvoidoperator=(Simple&/De-allocatedelete/TakeothersmemoryMemory=/Sincewehavetakenthetemporarys/Deta
54、chsOther.Memory=Youcansimplysay,Providetheplus(+)heclass. anoperator+Youcansimplysay,Providetheplus(+)heclass. anoperator+inourSimple(fortheobj3=obj1+obj2),andtheresourceis-enough!(Ihopeyouunderstanditfully beforeyoumoveto thenext paragraph.) the next sement(obj2=GetSimple()+obj1),theobject on the l
55、eft itself is temporary. Notet in SetSimple andhe move spel-functions, theargumentistemporary,his.Thereisnotechniquey class/GivestohelperfriendSimpleoperator+(Simple&left,constSimple&tomakethisatemporaryobject.Okay,okay,IamnotBjarneStroustrup;heretheNow,asyoucansee,atemporaryobjectiscreatedandisbein
56、greturned/ThismethodisINSIDEtheSimpleoperator+(constSimple/Dobinary+operationreturnSimpleobj1(10),obj2(20),obj3,obj4;/Pardonmeforusingsuchobj3=obj1 +obj2=GetSimple()+obj1; obj4=obj2+obj1+ (inshort,allthree)mustagreewiththesameprotocolforAnotherleme the Simple class we have been working on is some do
57、ntainer; like string, date/time, array, or anything you prefer.t dontaineriallow the following, with the help of operator overloading:Externalobj4 =obj2+obj1 +obj4=t1 +Externalobj4 =obj2+obj1 +obj4=t1 +obj4 =Hereitgoesinamoresimplified,non-verbalform(italicisthecallbeing, the normal class verofoperator+iscalled(forobj2+obj1).It returns a new Simpleobject, we call it t1.Now with t1 (theeofobj2+obj1),whichisatemporaryobject, operator+ gets called again (t1+obj3) - the out-of-class veroperator+is called, which takes ownership from t1.Theglobaloperato
溫馨提示
- 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)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 設(shè)計教育與設(shè)計師
- 全肺灌洗術(shù)的護(hù)理
- 脛骨截骨術(shù)的護(hù)理
- 山東省濰坊市壽光市達(dá)標(biāo)名校2025屆初三3月月考化學(xué)試題理試卷含解析
- 甘肅省臨夏地區(qū)夏河中學(xué)2024-2025學(xué)年高中新課程高三下學(xué)期期末考試英語試題含解析
- 福建省廈門市2025年四年級數(shù)學(xué)第二學(xué)期期末考試模擬試題含解析
- 朔州陶瓷職業(yè)技術(shù)學(xué)院《AutoCAD技術(shù)》2023-2024學(xué)年第二學(xué)期期末試卷
- 武漢紡織大學(xué)外經(jīng)貿(mào)學(xué)院《臨床檢驗儀器》2023-2024學(xué)年第一學(xué)期期末試卷
- 天津城市建設(shè)管理職業(yè)技術(shù)學(xué)院《高級法語1》2023-2024學(xué)年第一學(xué)期期末試卷
- 內(nèi)蒙古自治區(qū)呼倫貝爾市、興安盟達(dá)標(biāo)名校2025屆全國中考招生統(tǒng)一考試中考化學(xué)試題模擬試題(2)含解析
- 中國肝病診療管理規(guī)范
- 2025年世界知識產(chǎn)權(quán)日知識競賽考試題庫200題(含答案解析)
- 《燕麥的起源與早期傳播:從考古發(fā)現(xiàn)到歷史文獻(xiàn)的考證》論文
- 2025年上半年中國電子集團(tuán)總部16個崗位公開招聘16名易考易錯模擬試題(共500題)試卷后附參考答案
- 高速公路財務(wù)知識培訓(xùn)
- 2025年安陽職業(yè)技術(shù)學(xué)院單招職業(yè)適應(yīng)性測試題庫學(xué)生專用
- 園建工程施工方案
- 2025年科技節(jié)活動小學(xué)科普知識競賽題庫及答案(共200題)
- 2025-2030中國冶金設(shè)備行業(yè)市場深度分析及發(fā)展趨勢與投資戰(zhàn)略研究報告
- 郵政招聘筆試題庫及答案
- 第五屆綿陽市職業(yè)技能大賽賽項技術(shù)文件-焊工技術(shù)文件
評論
0/150
提交評論