Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to destroy a map that has pointer values

Tags:

c++

pointers

stl

I am using std::map to map string values to MyType *. My map declaration looks like this:

map<string, MyType *> *my_map = new map<string, MyType>;

my_map is a private member variable of one of my classes. My problem is that I am unsure of how to destroy the map. When deleteing the map, I would also like to call delete on all of the MyType * contained in the map. Here is my current destructor:

my_map->erase(my_map->begin(), my_map->end());
delete my_map;

Will this delete the pointers contained in the map, or do I need to iterate through the map to delete each pointer before calling erase?

like image 317
Max Avatar asked Jul 25 '13 14:07

Max


1 Answers

Pointers merely point. When using raw pointers, you need to know which part of your app owns the resources that the pointers point to. If they are owned by the map, you will need to iterate over the map and call delete on each pointer before the map is destroyed. But if the map just holds pointers to objects that are owned by other parts of your code, you don't need to do anything.

A safer solution is to use shared_ptr to manage object lifetime, which will ensure that the object gets deleted properly when the last shared_ptr is destroyed. You can store shared_ptrs inside the map and if no other shared_ptr instances reference the objects within the map, the objects will be destroyed when the map is destroyed, as desired.

like image 70
Kylotan Avatar answered Oct 09 '22 05:10

Kylotan