2015-02-08 58 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