【发布时间】:2013-08-22 21:21:22
【问题描述】:
我为 std::map 编写了一个比较函数,因此我可以拥有自定义键类型。
std::map<GGString *, GGObject *, GGDictionaryMapCompare> _map;
...
class GGDictionaryMapCompare
{
public:
bool operator()(GGString * lhs, GGString * rhs)
{
return strcmp(lhs->str(), rhs->str()) < 0;
}
};
添加元素的代码:
GGObject *GGDictionary::addKeyObject(GGString *theKey, GGObject *theObject)
{
if (theKey == NULL || theObject == NULL)
return NULL;
_map.insert(std::pair<GGString *, GGObject *>(theKey, theObject));
return theObject;
}
导致崩溃的代码:
GGObject *GGDictionary::objectForKey(GGString *theKey)
{
if (theKey == NULL)
return NULL;
std::map<GGString *, GGObject *, GGDictionaryMapCompare>::iterator ii = _map.find(theKey);
if (ii == _map.end())
return NULL;
return GGAutoRelease(ii->second);
}
堆栈跟踪:
#0 0x00009f15 in GGString::str()
#1 0x0004a4c4 in GGDictionaryMapCompare::operator()(GGString*, GGString*)
#2 0x0004a3d3 in std::_Rb_tree<GGString*, std::pair<GGString* const, GGObject*>, std::_Select1st<std::pair<GGString* const, GGObject*> >, GGDictionaryMapCompare, std::allocator<std::pair<GGString* const, GGObject*> > >::find(GGString* const&)
#3 0x00049b04 in std::map<GGString*, GGObject*, GGDictionaryMapCompare, std::allocator<std::pair<GGString* const, GGObject*> > >::find(GGString* const&)
#4 0x00048ec9 in GGDictionary::objectForKey(GGString*)
问题是 lhs 是 NULL。我从不在地图中插入 NULL,所以这不应该发生。知道为什么吗?还是我只是做错了比较功能?我可以防止获得 NULL,但似乎有问题,我不想治愈症状而不是问题。
谢谢
【问题讨论】:
-
显示你在哪里添加元素。
-
您能否发布一些有关您如何使用它和/或如何向地图添加元素的代码?我可以尝试重现该问题。我没有看到该代码有任何明显的问题,所以可能在实现中有些奇怪。
-
GGAutoRelease是做什么的? -
你确定指针真的是 NULL 而不仅仅是无效吗?
-
您确定没有在其他任何地方修改
_map,例如带有无意的_map[foo],其中foo是NULL?