簡體   English   中英

擦除包含共享指針的容器也會刪除所指向的對象?

[英]Erasing container that holds a shared pointer also deletes the object that's being pointed to?

例如,使用原始指針:

Object *obPointer = new Object(); //dynamically allocating memory, meaning we have to delete it, ourselves, later

std::unordered_map<std::string, Objects*> objContainer; //container that holds a string key and a pointer to an object type.

objContainer.emplace("A", obPointer); // placing a string and a pointer to an object into the container. simple enough.

現在,如果我們擦除該容器,它不會釋放我們分配的內存,即“對象”類型。 所以我們必須手動刪除它,對嗎?

delete obPointer;


objContainer.erase("A"); 

如果我們沒有刪除 obPointer,僅僅擦除容器是不夠的——我們會發生內存泄漏。 無論如何,當談到共享指針時,我不知道這是否有效,因為我們不會對它們調用 delete :

std::shared_ptr<Object> obPointer = std::make_shared<Object>(); //shared pointer

std::unordered_map<std::string, std::shared_ptr<Object>> container;

container.emplace("A", obPointer);

container.erase("A");

智能指針是否自行清理? 或者它只會在超出范圍時自行清理?

不管最后發生了什么

由於您有一個共享指針,它會跟蹤它存在的副本數量。 在您的情況下,您的本地范圍內有obPointercontainercontainer一個對象(因此總共有 2 個)。 在調用erasecontainer的對象被破壞並且計數返回到 1。當obPointer超出范圍時,計數變為 0 並且QObject實例被刪除。

所以,就像 Dave 提到的,我應該使用一個唯一的指針。 在我的示例中,通過擦除容器,它不會釋放使用 shared_ptr 分配的內存。 如果內存超出范圍或引用,它只會刪除內存。 因此,正如 Dave 所建議的,我使用了一個 unique_pointer 來創建內存,然后我使用“std::move”將其“傳遞”給容器,這將所有權轉移到容器的指針。 因此,一旦我擦除該容器,內存就會釋放。 像這樣:

//Container
std::unordered_map<std::string, std::unique_ptr<Object>> //container;
{//Scope just to demonstrate it works
 std::unique_ptr<Object> obPointer = std::make_unique<Object>(); //unique pointer

/*Now we transfer the ownership to the container, making its life spam
rely on the scope of the CONTAINER and the container itself*/
container.emplace("A", std::move(obPointer)); //std::move very important

}//only "obPointer" will die cuz of the scope, but it's null now. 
// the actual object that we created didn't delete itself. It's in the container



/*If we want to free up the memory, we should just erase the specific container
or wait for it to be out of the scope.*/
 container.erase("A"); //pointer deleted and memory freed

你去吧。 一種“手動”刪除智能指針的方法。 很有用。

暫無
暫無

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

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