取回後損壞的所以我已經編輯完成我的問題。 我有一個map
稱爲mTextMap
其中包含:對象在地圖從地圖
typedef std::map<const std::string, Text*> TextMap;
TextMap mTextMap;
而且我有以下幾種方法:
void Foo::setUpGame()
{
Text text(1,2,3,4); //create a Text object
mTextMap["MainText"] = &text; //save it in the map!
}
Text& Foo::getText(const std::string name)
{
auto i= mTextMap.find(name);
return *(i->second); //Gets a reference to the Text that is inside the map
}
現在,如果我用這樣的方式:
Foo foo;
foo.setUpGame();
Text& myText = foo.getText("MainText"); // Why is this corrupted?
對象myText
完全損壞!
這是怎麼發生的?
使用['unique_prt'](http://www.cplusplus.com/reference/memory/unique_ptr/)或['shared_prt'](http://www.cplusplus.com/reference/memory/shared_ptr/ )作爲地圖中的值類型。如果你是自己管理記憶,那很容易犯錯。 –
如果您願意,我們檢查了您的代碼,提供[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –
你爲什麼要存儲指向objs而不是obj本身的指針? – MikeMB