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