Assume I have some unordered_map
of pointers to class instances, would erasing an object from that map also delete the instance?
(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!
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, e.g.
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. Unless you have a very good reason to use new
and delete
, don't; 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With