从 std::map 中删除动态分配的内存
我有一张地图 std::map<字符串,A*> MyMap
,这里A是一个类;它的对象是使用“new”创建的,并像这样插入到地图中,
MyMap["first"] = new A();
MyMap["second"] = new A(); // second step
MyMap["third"] = new A();
像这样,我每 5 秒将动态创建的一个对象插入到数组中。在某些时候,我想释放使用“new”创建的内存,我不想删除所有项目。我只想释放地图上的少数项目。是否可以只删除特定项目占用的内存? (例如,我只想删除第二步中创建的 A 对象占用的空间。
I have a map std::map< string,A* > MyMap
, here A is a class; its object is created created using "new" and inserted into map like this,
MyMap["first"] = new A();
MyMap["second"] = new A(); // second step
MyMap["third"] = new A();
Like this, I am inserting dynamically created A object into array with in every 5 seconds. After some point I want to release the memory created using "new" I don't want to delete all the items. I want to free up only few items from map. Is it possible only delete the memory taken by particular items? ( For example I want to delete only the space taken for the A object which is created in second step.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确实。首先,获取要删除的对象的指针或引用。然后,使用map.erase()将其从地图中取出。现在,该对象仅保留您的指针或引用,因此您可以使用删除来释放其内存。
Definitely. First, obtain a pointer or reference to the object you want to remove. Then, take it out of the map using map.erase(). Now, the object is held only the your pointer or reference, so you can free up its memory using delete.