我在当前的C ++项目中使用unordered_map并存在以下问题:

当我在unordered_map中插入一对对象时,程序中断,Windows提示我“ [.... exe已停止工作”,而没有在控制台(cmd)上提供任何信息。一些示例代码:



#include <unordered_map>

#include <network/server/NetPlayer.h>
#include <gamemodel/Player.h>


int main(int argc, char **argv) {
    NetGame game;
    boost::asio::io_service io_service;

    NetPlayerPtr net(new NetPlayer(io_service, game));
    PlayerPtr player(new Player);

    std::unordered_map<PlayerPtr, NetPlayerPtr> player_map;

    // Here it breaks:
    player_map[player] = net;

    return 0;
}


我已经尝试过的

我尝试用try-catch来包装生产线,但没有成功。

有关代码的详细信息:

NetPlayerPtr和PlayerPtr是boost::shared_ptr对象,前者包含一些boost::asio对象,例如io_servicesocket,后者包含几个自定义对象。

我正在使用在64位Windows上启用C ++ 11的MinGW gcc进行编译。

如果需要更多详细信息,请询问。

最佳答案

好的,让我们看一下链接到的代码:

namespace std
{
    template<>
    class hash<Player>
    {
    public:
        size_t operator()(const Player &p) const
        {
            // Hash using boost::uuids::uuid of Player
            boost::hash<boost::uuids::uuid> hasher;
            return hasher(p.id);
        }
    };

    template<>
    class hash<PlayerPtr>
    {
    public:
        size_t operator()(const PlayerPtr &p) const
        {
            return hash<PlayerPtr>()(p);   // infinite recursion
        }
    };
}


您的hash<PlayerPtr>::operator()中具有无限递归。您可能想要的是:

return hash<Player>()(*p);


要么:

return hash<Player*>()(p->get());


取决于您是否要通过播放器的内部ID或地址来识别播放器。

09-07 07:00