java - 是否類 類型指針、引用作為形參 ,函數(shù)結(jié)束不會(huì)自動(dòng)析構(gòu)類?
問題描述
自動(dòng)析構(gòu)是在作用域結(jié)束時(shí)析構(gòu)作用域里創(chuàng)建的類對(duì)象的嗎?
問題解答
回答1:如果是用指針new出來的對(duì)象, 必須進(jìn)行手動(dòng)delete. 析構(gòu)函數(shù)不會(huì)幫你自動(dòng)析構(gòu), 比如std::string* s = new std::string;. 如果這是在一個(gè)類里面構(gòu)造的string, 這個(gè)類會(huì)將s回收, 但是不會(huì)將s指向的空間回收. 引用你只要記住其實(shí)就是一個(gè)別名就能做出自己的判斷了.
回答2:我不該講那么多有的沒的,而且我理解的不對(duì)。
在函數(shù)結(jié)束時(shí),只有聲明在函數(shù)體內(nèi)的自動(dòng)變量和函數(shù)的形式參數(shù)會(huì)被銷毀(destroyed),他們所引用的對(duì)象(若有),不會(huì)隨他們的銷毀而被銷毀。一個(gè)指針/引用所引用的對(duì)象有自己獨(dú)立的存儲(chǔ)期,這個(gè)對(duì)象何時(shí)被銷毀,取決于它自己的存儲(chǔ)期。
你在問題中問的是何時(shí)隱式調(diào)用析構(gòu)函數(shù)。析構(gòu)函數(shù)的隱式調(diào)用同樣取決于這個(gè)對(duì)象的存儲(chǔ)期。簡單的說,若對(duì)象被構(gòu)造,則析構(gòu)函數(shù)會(huì)在他被銷毀時(shí)被調(diào)用。
12.3.2.11 Destructors are invoked implicitly— for constructed objects with static storage duration (3.7.1) at program termination (3.6.3),— for constructed objects with thread storage duration (3.7.2) at thread exit,— for constructed objects with automatic storage duration (3.7.3) when the block in which an object is created exits (6.7),— for constructed temporary objects when the lifetime of a temporary object ends (12.2),— for constructed objects allocated by a new-expression (5.3.4), through use of a delete-expression (5.3.5),— in several situations due to the handling of exceptions (15.3).
關(guān)于引用:
引用不是對(duì)象,但他同樣有存儲(chǔ)期(存儲(chǔ)期對(duì)任何變量都適用)。存儲(chǔ)期的銷毀規(guī)則同樣適用于引用。但是在引用被銷毀時(shí)發(fā)生什么,我沒有找到準(zhǔn)確的描述。究竟引用如何被銷毀應(yīng)該是取決于編譯器實(shí)現(xiàn)。大概情況應(yīng)該是:如果引用在實(shí)現(xiàn)時(shí)占有存儲(chǔ)空間,則該空間會(huì)被回收。如果不占有,則什么都不會(huì)發(fā)生。(引用類型的形式參數(shù)在函數(shù)不被內(nèi)聯(lián)時(shí)常常會(huì)占有存儲(chǔ)空間)
3.7.3 The storage duration categories apply to references as well. The lifetime of a reference is its storage duration.
8.3.2.4 It is unspecified whether or not a reference requires storage.
3.9.8 An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
1.8 [...] An object is a region of storage. [ Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. — end note ] [...]
回答3:1.析構(gòu)函數(shù)是c++針對(duì)類引入的,是在類變量生命周期結(jié)束之后,空間被回收之前被調(diào)用的函數(shù)。2.類指針和類引用(指向變量的常指針)只是基本數(shù)據(jù)類型(指針),并沒有析構(gòu)函數(shù)之說,函數(shù)調(diào)用結(jié)束之后他們對(duì)應(yīng)的棧空間會(huì)被回收而已。3.如果參數(shù)傳遞的是類對(duì)象則就如第一點(diǎn)說的那樣,在空間被回收之前調(diào)用析構(gòu)函數(shù)。4.所有的棧上的類變量都會(huì)在生命周期結(jié)束后自動(dòng)析構(gòu),而堆上的類變量(new等操作分配的)則不會(huì),需要手動(dòng)釋放去觸發(fā)析構(gòu)函數(shù)的調(diào)用。
