本文介紹了在刪除指向動態(tài)分配對象的指針向量中的元素之前,我需要做什么?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我有一個用指向?qū)ο蟮闹羔樚畛涞南蛄?我正在努力學(xué)習(xí)良好的內(nèi)存管理,并有一些一般性問題:
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:
- 當(dāng)我處理完向量后,我必須遍歷它并對每個指針調(diào)用 delete 是真的嗎?
- 為什么我不必在沒有 new 語句的情況下對向量或我聲明的任何其他變量調(diào)用 delete,但必須對指針調(diào)用 delete?
- 如果向量是在返回的函數(shù)中聲明的(導(dǎo)致向量超出范圍),C++ 是否會為我處理釋放指針的內(nèi)存?
推薦答案
- 是的
- 向量是使用模板內(nèi)存分配器實現(xiàn)的,它們?yōu)槟?fù)責(zé)內(nèi)存管理,因此它們有些特殊.但作為一般經(jīng)驗法則,由于堆棧和堆分配之間的差異,您不必對未使用
new
關(guān)鍵字聲明的變量調(diào)用delete
.如果在堆上分配了東西,則必須將其刪除(釋放)以防止內(nèi)存泄漏. - 沒有.在遍歷所有元素時,您必須明確調(diào)用
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.
這篇關(guān)于在刪除指向動態(tài)分配對象的指針向量中的元素之前,我需要做什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!