简体   繁体   English

c ++ map erase()

[英]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. 当我对元素执行erase()时,这会释放内存还是只从地图中删除元素。

I actually need to keep the memory as is. 我实际上需要保持内存不变。 I just need to remove the element from the map since 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. STL容器无法管理您的内存,因此请确保执行此操作。 I almost always used boost's shared_ptr when putting objects into containers. 在将对象放入容器时,我几乎总是使用boost的shared_ptr

When you erase from a map<something,something_else*> , it only removes the element from the map. 当你erasemap<something,something_else*>它只是从地图上移除的元素。 It does not call the delete operator (or any other function) on the erased element to free memory. 它不会调用擦除元素上的delete操作符(或任何其他函数)来释放内存。

No, the objects referred to by the pointers in your map will not be deleted. 不,地图中指针引用的对象不会被删除。

Containers in the C++ standard library have value semantics. C ++标准库中的容器具有语义。 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. 如果您的环境支持,请使用boost_shared_ptr<>std::map< key, boost_shared_ptr<value> > )或std::tr1::shared_ptr<>std::shared_ptr<>来摆脱大多数与内存相关的问题。

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. 基本上,如果你创建了它,那么你需要销毁它。

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

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