c++ - 在 C++ 中调用虚函数时出现分段错误
问题描述
我目前正在为我的游戏引擎开发 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
,它也有一个有效的地址。问题是在调用它时。
解决方案
#ifndef SYSTEMTEST_H_
#define SYSTEMTEST_H_
#include <stdint.h>
#include <vector>
#include <iostream>
struct World
{
int id;
};
struct System{
public:
uint32_t id;
virtual void init(World* world){}
virtual void update(World* world){}
};
int systemID = 0;
std::vector<System*> systems;
struct Derived : System
{
void init(World* world){
std::cout << "init" << std::endl;
}
void update(World* world){
std::cout << "update" << std::endl;
}
};
uint32_t getID()
{
return systemID++;
}
template<typename T> void addSystem(){
T* system = new T();
system->id = getID();
//systems.append(system);
systems.push_back(system);
}
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;
}
}
//remove operator
//systems.remove(index);
}
#endif
#include <iostream>
#include "SystemTest.h"
using namespace std;
int main(int argc, char** argv){
addSystem<Derived>();
for (int i = 0; i < systems.size(); i++)
{
World *world;
world = new World;
systems[i]->init(world);
}
return 0;
}
我明白你的描述。
我试着完成剩下的
运行成功
推荐阅读
- python - 在 django 中管理 helper/utils 函数及其敏感数据
- java - 将几个相同的CDI bean注入一个类?
- json - 试图让我们 XSLT 从一个简单的 JSON 响应中提取一个值,但无法启动
- android - ignoreAssetsPattern 不适用于构建类型
- javascript - 将 Storybook Control 标签更改为其他名称
- python - 无论我将什么定义为 INPUT_VAR,它总是会打印出来。在这里,当我不希望它打印“Performing test on Lungs”时
- gatsby - 如何使用 Gatsby.js 和 SSR 创建动态路由?
- r - 如何在 lm() 函数中动态命名公式中的变量?
- postgresql - 如果通过 postgres 备份和恢复工具不存在创建数据库的问题
- javascript - 我不知道我在用这个正则表达式做错了什么,它应该匹配 id":" 和 "