簡體   English   中英

用指針在映射中釋放內存

[英]deallocating memory in a map with pointers

我試圖從映射中刪除指針元素(映射中的值是一個指針),並且在這里看到了代碼。 在VS,UNIX / Linux中刪除STL迭代器后,會發生什么?

for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) {
    // wilhelmtell in the comments is right: no need to check for NULL. 
    // delete of a NULL pointer is a no-op.
    if(it->second != NULL) {
        delete it->second;
        it->second = NULL;
    }
}

我不確定'delete it-> second'是否會取消分配正確的內存,因為delete(it ++)步驟已經將迭代器移至下一個對象。 到時候,它到達了delete語句,它指向我們不想刪除的下一個元素。 我想念什么嗎?

我相信這會按預期工作。

for循環的第三部分(先刪除迭代器,然后再遞增迭代器) 第一次迭代之后執行,依此類推。 因此,您總是要擦除循環內容中已經“處理”的元素。

一個平行的例子:

for (int i = 0; i < 1; ++i) { ...

在增加i並檢查循環條件之前,您仍將進入循環並以i = 0執行。

您可能想嘗試另一種方法:

while (T2pS.size() > 0) {
  if (T2pS.begin()->second != NULL) {
    delete T2pS.begin()->second;
  }
  T2pS.erase(T2pS.begin());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM