I have query regarding std::map.
if I have a std::map like:
std::map <T1, T2*> my_map;
T1 t;
T2* tt = new T2;
my_map[t]=tt;
who is responsible to clean this container, Will destructor of T2 will take care of it (T2* tt). Also if I want to retain this container throughout the program, where should I clean it.
Thanks
The map destroys the objects stored in the map. The map stores some
T1objects, which will be destroyed, and it stores someT2pointers, which will be destroyed.But it does not store actual
T2objects. So noT2objects will be destroyed.Raw pointers do not have ownership of the objects they point to. So when a pointer is destroyed, it will not delete whatever it points to.
Generally speaking, when you have a pointer, there is no way to know if
deleteon some random garbage in memory),new(if it has been allocated in another way, it should not be deleted withdelete), ordelete. Which one?)So even if you wanted to, there is no way to automatically delete an object when a pointer to it is destroyed.