2012-12-21 29 views
0

我在當前的C++項目中使用unordered_map,並有以下問題:unordered_map shared_ptrs的突破C++程序

當我插入一對對象進入unordered_map,在PROGRAMM休息和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,後者包含幾個自定義對象。

我正在用MinGW gcc編譯,在64位Windows上啓用C++ 11。

如果需要更多的細節,請詢問。

+3

你試過調試器嗎? –

+0

不,我沒有像GDB這樣的調試器的使用經驗(如果你正在談論這個)。 – msiemens

+7

@ m - s現在是你的機會! – 2012-12-21 10:54:47

回答

3

好吧,讓我們來看看你的代碼鏈接到:

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()的inifinite遞歸。你可能想要的是:

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

或:

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

取決於你是否希望通過其內部的ID或地址來識別玩家。

+1

嗯......我需要爲一個變量提供'hash'。哦,讓我們只是'std :: hash'吧!天才! :) –

+0

是的,這解決了它。非常感謝! :) – msiemens