c++ map erase()
I have a map in which my value is dynamically allocated. When I do erase() on an element, does this free the memory OR just removes the element from the map.
I actually need to keep the memory as is. I just need to remove the element from the map si开发者_如何学JAVAnce this dynamically allocated structure is used elsewhere in the code.
No it doesn't free the memory if it is a naked pointer. You need to ensure that the memory is deallocated appropriately.
If you're using a naked pointer then make sure you clean up the memory properly when you need to.
If you're using a smart pointer and the map holds the last reference to the object, then the memory will be cleaned up by the smart pointer's destructor when the map erases it.
STL containers won't manage your memory, so ensure you do it. I almost always used boost's shared_ptr
when putting objects into containers.
When you erase
from a map<something,something_else*>
, it only removes the element from the map. It does not call the delete
operator (or any other function) on the erased element to free memory.
No, the objects referred to by the pointers in your map will not be deleted.
Containers in the C++ standard library have value semantics. They will destroy the objects you put into them. When those objects are pointers, these pointers will be destroyed, but not the objects they are referring to.
Use boost_shared_ptr<>
(std::map< key, boost_shared_ptr<value> >
) or std::tr1::shared_ptr<>
or std::shared_ptr<>
, if your environment supports it, to get rid of most memory related issues.
The standard containers will never destroy dynamically allocated objects that you place in them when you erase the elements. Basically, if you created it then you need to destroy it.
精彩评论