我有一个 map<string, std::function<void(AgentMessage&)>>
(AgentMessage 是一个带有几个字符串的结构)。当我尝试使用迭代器访问它时,我在 pair
的复制函数上遇到访问冲突.
注意:std::function 指向与它被复制的地方不同的 dll 中的函数。
编辑:我认为解释对于一段简单的代码来说已经足够好了,但仍然 - 就在这里。
for (map<string, std::function<void(AgentMessage&)>>::iterator it = mapRef.begin(); it != mapRef.end(); it++)
{
auto functionCopy = it->second; // IT CRASHES HERE
}
最佳答案
你能展示将元素插入 map 的代码吗?
我试过了,效果很好:
#include <functional>
#include <map>
#include <string>
using namespace std;
struct AgentMessage
{
};
void f(AgentMessage& am)
{
}
void g(AgentMessage& am)
{
}
int main()
{
AgentMessage am;
map<string, std::function<void(AgentMessage&)>> m;
m["f"] = f;
m["g"] = g;
for (map<string, std::function<void(AgentMessage&)>>::iterator it = m.begin(); it != m.end(); ++it)
{
auto func = it->second;
func(am);
}
}
关于c++访问 map 时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226304/