正确地销毁std :: map中的指针 [英] Properly destroying pointers in an std::map
问题描述
我有一个映射声明为
std::map<std::string, Texture*> textureMap;
我用来将纹理文件的路径与实际纹理配对,以便我可以引用纹理通过路径没有加载相同的纹理一堆次的个别精灵。我不知道该怎么办是正确地破坏ResourceManager类(其中的地图是)的析构函数中的纹理。
which I use for pairing the path to a texture file to the actual texture so I can reference the texture by the path without loading the same texture a bunch of times for individual sprites. What I don't know how to do is properly destroy the textures in the destructor for the ResourceManager class (where the map is).
我想过使用一个循环这样的迭代器:
I thought about using a loop with an iterator like this:
ResourceManager::~ResourceManager()
{
for(std::map<std::string, Texture*>::iterator itr = textureMap.begin(); itr != textureMap.end(); itr++)
{
delete (*itr);
}
}
但这不起作用,指针。这是很晚,所以我可能只是错过了一些明显的东西,但我想让它在睡觉前工作。
But that doesn't work, it says delete expected a pointer. It's pretty late so I'm probably just missing something obvious, but I wanted to get this working before bed. So am I close or am I totally in the wrong direction with this?
推荐答案
就你的示例代码而言,你需要在循环中这样做:
As far as your sample code goes, you need to do this inside the loop:
delete itr->second;
地图有两个元素,您需要删除第二个元素。在你的情况下, itr->第一
是一个 std :: string
和 itr- >第二
是纹理*
。
The map has two elements and you need to delete the second. In your case, itr->first
is a std::string
and itr->second
is a Texture*
.
如果您需要删除特定条目,您可以这样做:
If you need to delete a particular entry, you could do something like this:
std::map<std::string, Texture*>::iterator itr = textureMap.find("some/path.png");
if (itr != textureMap.end())
{
// found it - delete it
delete itr->second;
textureMap.erase(itr);
}
您必须确保地图中存在该条目,否则您可能会得到尝试删除纹理指针时出现异常。
You have to make sure that the entry exists in the map otherwise you may get an exception when trying to delete the texture pointer.
另一种方法是使用 std :: shared_ptr
原始指针,然后您可以使用更简单的语法从地图中删除项目,并让 std :: shared_ptr
处理删除的基础对象。这样,你可以使用 erase()
和一个关键参数,例如:
An alternative might be to use std::shared_ptr
instead of a raw pointer, then you could use a simpler syntax for removing an item from the map and let the std::shared_ptr
handle the deletion of the underlying object when appropriate. That way, you can use erase()
with a key argument, like so:
// map using shared_ptr
std::map<std::string, std::shared_ptr<Texture>> textureMap;
// ... delete an entry ...
textureMap.erase("some/path.png");
这将做两件事:
- 从地图中删除条目(如果存在)
- 如果没有其他引用
Texture *
,对象将被删除
- Remove the entry from the map, if it exists
- If there are no other references to the
Texture*
, the object will be deleted
要使用 std :: shared_ptr
您需要最近的C ++ 11编译器,或 Boost 。
In order to use std::shared_ptr
you'll either need a recent C++11 compiler, or Boost.
这篇关于正确地销毁std :: map中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!