java - 是否類 類型指針、引用作為形參 ,函數(shù)結(jié)束不會自動析構(gòu)類?
問題描述
自動析構(gòu)是在作用域結(jié)束時析構(gòu)作用域里創(chuàng)建的類對象的嗎?
問題解答
回答1:如果是用指針new出來的對象, 必須進行手動delete. 析構(gòu)函數(shù)不會幫你自動析構(gòu), 比如std::string* s = new std::string;. 如果這是在一個類里面構(gòu)造的string, 這個類會將s回收, 但是不會將s指向的空間回收. 引用你只要記住其實就是一個別名就能做出自己的判斷了.
回答2:我不該講那么多有的沒的,而且我理解的不對。
在函數(shù)結(jié)束時,只有聲明在函數(shù)體內(nèi)的自動變量和函數(shù)的形式參數(shù)會被銷毀(destroyed),他們所引用的對象(若有),不會隨他們的銷毀而被銷毀。一個指針/引用所引用的對象有自己獨立的存儲期,這個對象何時被銷毀,取決于它自己的存儲期。
你在問題中問的是何時隱式調(diào)用析構(gòu)函數(shù)。析構(gòu)函數(shù)的隱式調(diào)用同樣取決于這個對象的存儲期。簡單的說,若對象被構(gòu)造,則析構(gòu)函數(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)于引用:
引用不是對象,但他同樣有存儲期(存儲期對任何變量都適用)。存儲期的銷毀規(guī)則同樣適用于引用。但是在引用被銷毀時發(fā)生什么,我沒有找到準確的描述。究竟引用如何被銷毀應(yīng)該是取決于編譯器實現(xiàn)。大概情況應(yīng)該是:如果引用在實現(xiàn)時占有存儲空間,則該空間會被回收。如果不占有,則什么都不會發(fā)生。(引用類型的形式參數(shù)在函數(shù)不被內(nèi)聯(lián)時常常會占有存儲空間)
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++針對類引入的,是在類變量生命周期結(jié)束之后,空間被回收之前被調(diào)用的函數(shù)。2.類指針和類引用(指向變量的常指針)只是基本數(shù)據(jù)類型(指針),并沒有析構(gòu)函數(shù)之說,函數(shù)調(diào)用結(jié)束之后他們對應(yīng)的棧空間會被回收而已。3.如果參數(shù)傳遞的是類對象則就如第一點說的那樣,在空間被回收之前調(diào)用析構(gòu)函數(shù)。4.所有的棧上的類變量都會在生命周期結(jié)束后自動析構(gòu),而堆上的類變量(new等操作分配的)則不會,需要手動釋放去觸發(fā)析構(gòu)函數(shù)的調(diào)用。
