【发布时间】:2015-02-08 15:18:16
【问题描述】:
我已经在互联网上阅读了很多关于此错误以及为什么会导致此错误的信息,但我无法在我的代码中找到错误。
我有一个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);
}
但是每当返回对这个Inventory对象的引用时,GameObject类中的成员变量(id,name)就无法从内存中读取:
【问题讨论】:
-
离题,但可能有用:About inheriting from STL containers
-
这段代码将大大受益于smart pointers的使用
-
只是为了确保,您是否知道
m_inventory最终继承自std::list<GameObject**>?我认为一个*就足够了,但我不确定您的代码是否需要两个。 -
如果是这样,我建议重命名
Inventory类的模板参数,以将其与同名的类区分开来。可能会消除一些混乱。
标签: c++ list templates pointers inheritance