指向对象的指针数组返回jibberish

Array of pointers to objects returns jibberish

本文关键字:数组 返回 jibberish 指针 对象      更新时间:2023-10-16

晚上好,

我的任务是创建一个数组来容纳游戏中的所有对象。遗憾的是,所有这些对象都是在不同的地方创建的——手动将它们放入数组会很乏味——事实上,如果它们在创建它们的地方,但引用存储在数组中,我会感觉更好。。指针形式的引用。

所以,这就是我到目前为止所发现的,我已经这样做了,指向对象的每个实例的指针都被添加到构造函数中的数组中,如下所示:

const int GAME_MAX_ENTS = 65536;
class Object
{
public:
static Object* list[GAME_MAX_ENTS];
char type[64] = "ENT_OBJECT";
Object();
~Object();
};
Object::Object()
{
for (int i = 0; i < GAME_MAX_ENTS; i++)
{
if (!list[i])
{
list[i] = this;
break;
}
}
}
Object* Object::list[GAME_MAX_ENTS];

现在,我的问题是——当我试图查看该列表并在与创建对象的范围不同的范围中显示"type"的值时,它会弹出一些无稽之谈——我假设它是随机内存输出。

以下是我试图弹出正确信息的部分:

static void OnRender()
{
//Grid
SDL_RenderClear(renderer);
//Draw objects
for (int i = 0; i < GAME_MAX_ENTS; i++)
{
if (Object::list[i])
{
Object* obj = Object::list[i];
printf("%sn", obj->type);
}
}
[...]

为了让一切尽可能清楚,这里是我创建对象的部分——请注意,Tile只是一个继承自Object:的类

static void Initialize()
{
[...]
Tile tile;
Object obj;
}

我很确定这都是因为我缺乏C++的经验,我只是一个网络开发人员/C#擦洗-不要对我太苛刻^^

看起来您在Initialize()中创建的对象超出了范围。在C++中,您必须管理自己的内存(当使用指针时)。存储指向对象的指针并不能防止它被销毁。

您需要存储对象的副本,或者使用new显式创建对象,然后管理指针(或者使用C++智能指针来帮助您管理它们)。

您应该保留指向对象的指针,使它们在构造时自动添加,在销毁时自动删除。这样做的一种方法是有一个观察指针的set

// file object.h
namespace game {
struct object  // all game objects are derived from this
{
static set<const object*> const&list();  // return list of all objects
virtual draw() const;                    // example of virtual function
object();                                // only ctor: add this to list
object(object const&) = delete;          // disable copy ctor of base
virtual ~object();                       // dtor: remove this from list
};
}
// file object.cc
#include "object.h"
#include <set>
#include <mutex>
namespace {
std::mutex protect_object_list;
std::set<const object*> object_list;
}
std::set<const object*> const& object::list()
{
return object_list;
}
object::object()
{
std::lock_guard<std::mutex> lock(protect_object_list);
object_list.insert(this);
}
object::~object()
{
std::lock_guard<std::mutex> lock(protect_object_list);
object_list.erase(this);
}

用法可能看起来像

#include "object.h"
namespace game {
struct tile : object
{
void draw() const override;
tile(position const&pos) : object() { /* ... */ }
tile(tile const&t) : object() { /* ... */ }
};
void draw_objects()
{
for(auto const&obj:object::list())
obj.draw();
}
}

通过这种方式,object::list中的对象通过指针比较进行排序。如果您想要另一个排序,您可能需要使用std::map<size_t,const object*>,并使用在构造对象时递增的静态计数器作为键。