我目前正在为我的游戏引擎开发 C++ 中的 ECS。我有一个基本系统结构,它有两个虚函数init()
,并update()
在派生结构中实现。我有一个使用模板的addSystem()
和removeSystem()
函数,并且我有一系列System*
系统。如果我尝试调用它们,它会给我一个分段错误。
系统:
struct System{
public:
uint32_t id;
virtual void init(World* world){}
virtual void update(World* world){}
};
添加系统():
template<typename T>
void addSystem(){
T* system = allocate<T>();
system->id = getID();
systems.append(system);
#ifdef DEBUG
LOG("ECS: System added successfully.");
#endif // DEBUG
}
删除系统():
template<typename T>
void removeSystem(uint32_t id){
unsigned int index;
for(int i = 0; i < systems.size; i++){
if (systems[i]->id == id){
index = i;
break;
}
}
systems.remove(index);
}
从 System* 调用虚函数:
for (int i = 0; i < systems.size; i++){
systems[i]->init(this); // Here is the segmentation fault.
}
for (int i = 0; i < systems.size; i++){
systems[i]->update(this); // Here is the segmentation fault.
}
请询问是否需要更多信息。
编辑:
size
在 for 循环中等于 1 并且 systems[i] 是一个有效的指针。我也测试过p systems[i]->update
,它也有一个有效的地址。问题是在调用它时。