我正在尝试删除以下地图:
typedef bool (myClass::*func)(std::vector<std::string> &args);
typedef std::map<std::string, func> myMap;
myMap map; //map of functions in the class 'myClass'
void deleteMap()
{
for(myMap::iterator it = map.begin(); it != map.end(); ++it)
{
delete it->second; //compiler says it->second is non-pointer type
map.erase(it);
}
}
Run Code Online (Sandbox Code Playgroud)
'map' 将字符串映射到类 'myClass' 中的函数,该函数在其参数中采用字符串向量。
在我尝试删除此映射时,我试图删除指向成员函数的指针,然后擦除迭代器本身。编译器说 it->second 必须是指针类型。在 typdef 'func' 是一个指向 myClass:: 的指针,那么为什么我会收到这个错误?
这是删除函数映射的合适方法吗?
你在这里误解了一些概念。您使用delete
/delete[]
分别释放已由new
/分配的内存new[]
。
在这里,您有一个std::map
存储指向成员函数值的指针。堆上没有分配内存new
,因此您根本不必释放内存 using delete
。
除此之外,您不需要std::map::erase()
对每个元素都使用。相反,您可以使用要么std::map::clear()
清除std::map
,要么只是让析构函数std::map
自动释放内容。
归档时间: |
|
查看次数: |
1112 次 |
最近记录: |