std::map 比较函数和 NULL

Rog*_*rat 3 c++ stl

我为 std::map 编写了一个比较函数,因此我可以拥有自定义键类型。

std::map<GGString *, GGObject *, GGDictionaryMapCompare> _map;
Run Code Online (Sandbox Code Playgroud)

...

class GGDictionaryMapCompare
{
public:
    bool operator()(GGString * lhs, GGString * rhs)
    {
        return strcmp(lhs->str(), rhs->str()) < 0;
    }
};
Run Code Online (Sandbox Code Playgroud)

添加元素的代码:

GGObject *GGDictionary::addKeyObject(GGString *theKey, GGObject *theObject)
{
    if (theKey == NULL || theObject == NULL)
        return NULL;

    _map.insert(std::pair<GGString *, GGObject *>(theKey, theObject));

    return theObject;
}
Run Code Online (Sandbox Code Playgroud)

导致崩溃的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

#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*)
Run Code Online (Sandbox Code Playgroud)

问题是 lhs 是 NULL。我从来没有在地图中插入 NULL,所以这不应该发生。知道为什么吗?或者我只是做错了比较功能?我可以防止获得 NULL,但似乎出了点问题,我不想治愈症状而不是问题。

谢谢

tem*_*def 5

在这段代码中:

GGObject *GGDictionary::objectForKey(GGString *theKey)
{
    std::map<GGString *, GGObject *, GGDictionaryMapCompare>::iterator ii = _map.find(theKey);
    if (ii == _map.end())
        return NULL;

    return GGAutoRelease(ii->second);
}
Run Code Online (Sandbox Code Playgroud)

你不是在检查是否theKeyNULL。因此,当在theKey和 的任何元素上调用比较器时map,您将取消引用NULL

要解决此问题,请尝试添加NULL检查:

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);
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!