【问题标题】:C++ Error reading characters of stringC ++错误读取字符串的字符
【发布时间】: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类中的成员变量(idname)就无法从内存中读取:

【问题讨论】:

  • 离题,但可能有用:About inheriting from STL containers
  • 这段代码将大大受益于smart pointers的使用
  • 只是为了确保,您是否知道m_inventory 最终继承自std::list&lt;GameObject**&gt;?我认为一个* 就足够了,但我不确定您的代码是否需要两个。
  • 如果是这样,我建议重命名 Inventory 类的模板参数,以将其与同名的类区分开来。可能会消除一些混乱。

标签: c++ list templates pointers inheritance


【解决方案1】:

在第二个代码块中,push_back() 是一个指向局部变量的指针(即GameObject* item)。它在返回时被破坏,并使 IDE 指出此错误。

【讨论】:

  • 最好重新检查一下。在我看来,item 是使用new 在堆上分配的,因此在函数返回时不会销毁。
  • item指向的item没有被销毁,但是他使用了一个指向指针本身的指针,这个指针是一个局部变量。
  • 好的,我现在看到了,但是我不能这样写:(*inv).push_back(item);
  • 要么在堆上分配指针(至少在我看来这很奇怪),要么重写 push_back 以按值复制指针。
【解决方案2】:

我建议改变这个:

Inventory<GameObject*> m_inventory;

到这里:

Inventory<GameObject> m_inventory;

所以它将是std::list&lt;GameObject*&gt; 而不是std::list&lt;GameObject**&gt;

存储指向GameObject 的指针似乎是多余的,只存储指向GameObject 的指针就足够了,并且可以使您的其他代码更简单(例如这一行:(*inv).push_back(&amp;item))。

【讨论】:

  • 非常感谢,我认为这就是我所有问题的原因
  • 我认为所有问题的原因是 GameObject 类和 GameObject 模板参数具有相同的名称;) 模板参数应命名为 T 或类似简单的名称像这样消除混乱。
【解决方案3】:

我最近遇到了这个问题,是因为我在函数顶部声明了变量然后又声明了它。

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 2016-01-16
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    相关资源
    最近更新 更多