本文介紹了在刪除指向動態分配對象的指針向量中的元素之前,我需要做什么?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我有一個用指向對象的指針填充的向量.我正在努力學習良好的內存管理,并有一些一般性問題:
I have a vector that I fill with pointers to objects. I am trying to learn good memory management, and have a few general questions:
- 當我處理完向量后,我必須遍歷它并對每個指針調用 delete 是真的嗎?
- 為什么我不必在沒有 new 語句的情況下對向量或我聲明的任何其他變量調用 delete,但必須對指針調用 delete?
- 如果向量是在返回的函數中聲明的(導致向量超出范圍),C++ 是否會為我處理釋放指針的內存?
推薦答案
- 是的
- 向量是使用模板內存分配器實現的,它們為您負責內存管理,因此它們有些特殊.但作為一般經驗法則,由于堆棧和堆分配之間的差異,您不必對未使用
new
關鍵字聲明的變量調用delete
.如果在堆上分配了東西,則必須將其刪除(釋放)以防止內存泄漏. - 沒有.在遍歷所有元素時,您必須明確調用
delete myVec[index]
.
- Yes
- Vectors are implemented using template memory allocators that take care of the memory management for you, so they are somewhat special. But as a general rule of thumb, you don't have to call
delete
on variables that aren't declared with thenew
keyword because of the difference between stack and heap allocation. If stuff is allocated on the heap, it must be deleted (freed) to prevent memory leaks. - No. You explicitly have to call
delete myVec[index]
as you iterate over all elements.
例如:
for(int i = 0; i < myVec.size(); ++i)
delete myVec[i];
話雖如此,如果您打算將指針存儲在向量中,我強烈建議使用 boost::ptr_vector
自動處理刪除.
With that said, if you're planning on storing pointers in a vector, I strongly suggest using boost::ptr_vector
which automatically takes care of the deletion.
這篇關于在刪除指向動態分配對象的指針向量中的元素之前,我需要做什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!