我一直在網上閱讀了很多關於這個錯誤的信息,爲什麼會出現這種錯誤,但是我在代碼中找不到錯誤。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
類的成員變量(id
,name
)無法從內存中讀取:
偏離主題,但可能有用:[關於從STL容器繼承](http://stackoverflow.com/questions/2034916/is-it-okay-to-inherit-implementation-from-stl-containers-而不是委託) – emlai 2015-02-08 15:25:44
此代碼將從[智能指針]的使用中受益匪淺(http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i -use-one) – Edward 2015-02-08 15:32:28
只是爲了確認,你是否知道'm_inventory'結束了從'std :: list'的繼承?我認爲'*'就足夠了,但我不確定你的代碼是否需要兩個。 –
emlai
2015-02-08 15:37:23