首页 > 解决方案 > 在 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,它也有一个有效的地址。问题是在调用它时。

标签: c++segmentation-faultentity-component-system

解决方案


#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;

}

我明白你的描述。

我试着完成剩下的

运行成功


推荐阅读