2015-02-08 56 views
-1

我一直在網上閱讀了很多關於這個錯誤的信息,爲什麼會出現這種錯誤,但是我在代碼中找不到錯誤。C++讀取字符串的錯誤

我有一個Inventory類繼承的名單GameObject指針:

#ifndef INVENTORY_H 
#define INVENTORY_H 
#include "GameObject.h" 
#include <list> 

template <class GameObject> 
class Inventory : public std::list<GameObject*> 
{ 
    private: 
    public: 
     Inventory() : std::list<GameObject*>::list() {} 
}; 

#endif 

GameObject類看起來是這樣的:

class GameObject : public Updateable 
{ 
private: 
    ... 
    Inventory<GameObject*> m_inventory; 
public: 
    ... 
    void SetInventory(Inventory<GameObject*> inventory); 
    Inventory<GameObject*>& GetInventory(); 
}; 

然後,我通過這個方法填充新Inventory對象:

Inventory<GameObject*>& GameInitializer::ConfigureItems(XMLElement* xmlGameObject) { 
    Inventory<GameObject*>* inv = new Inventory<GameObject*>(); 
    ... 

    while (currElement != NULL) { 
     GameObject* item = new GameObject(); 
     // Configure all properties of the item 
     item->SetId(currElement->Attribute("id")); 
     item->SetPropertyHolder(ConfigureProperties(currElement)); 
     item->SetName(item->GetPropertyHolder().GetProperty("NAME").As<string>()); 
     // Add item to inventory 
     (*inv).push_back(&item); 
     currElement = currElement->NextSiblingElement(); 
    } 
    return (*inv); 
} 

但是whe從來沒有這種Inventory對象的引用返回,在GameObject類的成員變量(idname)無法從內存中讀取:

enter image description here

+0

偏離主題,但可能有用:[關於從STL容器繼承](http://stackoverflow.com/questions/2034916/is-it-okay-to-inherit-implementation-from-stl-containers-而不是委託) – emlai 2015-02-08 15:25:44

+0

此代碼將從[智能指針]的使用中受益匪淺(http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i -use-one) – Edward 2015-02-08 15:32:28

+1

只是爲了確認,你是否知道'm_inventory'結束了從'std :: list '的繼承?我認爲'*'就足夠了,但我不確定你的代碼是否需要兩個。 – emlai 2015-02-08 15:37:23

回答

3

在你的第二個代碼塊你push_back()指向一個局部變量(即GameObject* item)。它在返回時被破壞,並使IDE指出這個錯誤。

+1

更好地重新檢查一下。它看起來'item'是使用'new'在堆上分配的,因此當函數返回時不會被銷燬。 – Edward 2015-02-08 15:35:43

+0

'item'指向的項目沒有被銷燬,但是他使用了一個指向它自己的指針,這是一個局部變量。 – Downvoter 2015-02-08 15:36:29

+0

你是對的 - 我錯過了。 – Edward 2015-02-08 15:37:21

2

我建議改變這個:

Inventory<GameObject*> m_inventory; 

這樣:

Inventory<GameObject> m_inventory; 

所以這將是一個std::list<GameObject*>而不是std::list<GameObject**>

存儲指針到指針-TO-GameObject元素似乎是多餘的,並存儲只是會指向GameObject應該是不夠的,讓你的其他代碼更簡單(如這一行:(*inv).push_back(&item))。

+0

非常感謝你,這就是我認爲的所有問題的原因 – 2015-02-08 15:58:25

+0

我認爲你所有問題的原因是''GameObject'類和'GameObject'模板參數具有相同的名稱;)應該命名模板參數'T'或者類似的簡單東西來清除這樣的混亂。 – emlai 2015-02-08 15:59:58