正在删除 std::map 个函数

Deleting std::map of functions

我正在尝试删除以下地图:

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);
    }
}

'map' 将字符串映射到 class 'myClass' 中的一个函数,该函数在其参数中采用字符串向量。

在尝试删除此映射时,我试图删除指向成员函数的指针,然后擦除迭代器本身。编译器说 it->second 必须是指针类型。在 typdef 'func' 中是指向 myClass:: 的指针,那么为什么我会收到此错误?

这是删除函数映射的合适方法吗?

In my attempt to delete this map I am trying to delete the pointer to the member function,

该语言不允许这样做。您只能在对象指针上调用 delete

想想这个。

int (*fptr)(const char *lhs, const char *rhs ) = &std::strcmp;

 // Does it make any sense at all?
 // What would you expect the run time to do with this?
delete fptr;

你的函数可以很简单。你可以直接清除地图。

void deleteMap()
{
   map.clear();
}

您不能 delete 成员指针,因为它是 class 实例的一部分。

您没有发布向 myMap 添加元素的代码,但此类代码无法在类型 func 上创建带有 new 的成员指针,这表明delete 是错误的,因为每个 delete 必须由 new.

匹配

您只需调用 myMap.clear() 即可删除 myMap 的内容。

你误解了这里的一些概念。您使用 delete/delete[] 释放已分别由 new/new[] 分配的内存。

在这里,您有一个 std::map 存储指向成员函数值的指针。 new 没有在堆上分配内存,因此您根本不必使用 delete 释放内存。

除此之外,您不需要使用 std::map::erase() for every element. Instead, you might use either std::map::clear() 清除 std::map,或者让 std::map 的析构函数自动释放内容。

有时 pointer 可能指代不同类型的指针作为一个整体,但通常,例如在这种情况下,它特指 data pointer。你的指针是一个成员函数指针,因此它不是你的编译器所指的指针类型。

只能将数据指针传递给 delete 运算符,否则程序格式错误。更具体地说,您只能传递由 new 运算符 return 编辑的指针值。换句话说,delete 用于释放您使用 new.

分配的动态内存

new 运算符永远不能 return 一个(成员)函数指针,所以你的函数指针不可能 return 被 new 编辑。

Is this the appropriate way to delete a map of functions?

没有。您不能 "delete" 映射指向的函数。

map::erase 从映射中删除函数指针,但在删除该迭代器后递增该迭代器具有未定义的行为。因此,无法像您尝试的那样简单地实现循环擦除。

如果要删除所有指针,直接调用map::clear会更简单。第三,当地图本身被销毁时,所有内容也会自动销毁。

静态存储时长的对象,比如你的地图,会在程序结束时自动销毁,不能自己删除。