简体   繁体   English

的std :: unordered_map <std::String, myClass*> - std :: unordered_map :: erase()调用myClass&#39;DTor?

[英]std::unordered_map<std::String, myClass*> - does std::unordered_map::erase() call myClass' DTor?

Assume I have some unordered_map of pointers to class instances, would erasing an object from that map also delete the instance? 假设我有一些指向类实例的指针的unordered_map ,从该映射中删除一个对象也会删除该实例?

(rewording the question:) If I wanted to delete that instance, which version would be right? (重写问题:)如果我想删除该实例,哪个版本是正确的?

if(it != map.end())
{
    delete it->second;
    map.erase(it);
}

or simply 或者干脆

if(it != map.end())
    map.erase(it);

?

UPDATE: as suggested by many people, I moved to using shared_ptr , and it works great! 更新:正如许多人所建议的那样,我开始使用shared_ptr ,它运行得很好!

No, and since this is tagged C++11 you should be using std::unique_ptr / std::shared_ptr to manage your object pointers in the first place, eg 不,因为这是标记C ++ 11,你应该首先使用std::unique_ptr / std::shared_ptr来管理你的对象指针,例如

std::unordered_map<std::string, std::unique_ptr<myClass>>

Even if you religiously make sure that your pointers are delete d before any call to erase , you still have to consider what would happen in the event of an exception, or if you assign something else to the same key, or any number of other possibilities that might leak. 即使你虔诚地确保您的指针是delete任何调用之前d erase ,你还是要考虑会发生什么,在出现异常的情况下,或者如果你指定别的东西相同的密钥,或任意数量的其他可能性可能会泄漏。 Unless you have a very good reason to use new and delete , don't; 除非你有充分的理由使用newdelete ,否则不要; stick to std::unique_ptr / std::shared_ptr and std::make_unique / std::make_shared , it's safer and makes your code easier to read. 坚持使用std::unique_ptr / std::shared_ptrstd::make_unique / std::make_shared ,它更安全,使您的代码更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM