簡體   English   中英

在 C++ 中調用虛函數時出現分段錯誤

[英]Segmentation fault when calling virtual function in 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.
}

請詢問是否需要更多信息。

編輯:for 循環中的size等於 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;

}

我明白你的描述。

我試着完成剩下的

運行成功

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM