抛出例外:阅读访问违规.访问数组中的指针时

Exception thrown: read access violation. when accessing pointer in array

本文关键字:数组 访问 指针 读访问      更新时间:2023-10-16

我在尝试调用存储在CollidersBylayer中的类中的方法时会出现错误

static map<int, vector<Collider*>> collidersByLayer;
//Called twice by both a player and a box
void AddCollider(Collider collider, int layer) {
    //outputs either 640 for the player or 840 for the box
    cout << collider.GetPosition().x << endl;
    //checks if a layer already exists, if not make a new entry in the map
    if (collidersByLayer.find(layer) == collidersByLayer.end()) {
        collidersByLayer[layer] = vector<Collider*>();
    }
    //add the reference to the collider
    collidersByLayer[layer].push_back(&collider);
    //loop through the collidersByLayer map
    for (auto const& x : collidersByLayer) {
        vector<Collider*> colliders = x.second;
        for (size_t c = 0; c < colliders.size(); c++) {
            //the first time this runs fine, and outputs the position of the player (640).
            //when this function is called for the second time,
            //it gives me this error while trying to print the players position:
            //Exception thrown: read access violation.
            //__imp_sf::Transformable::getPosition(...) returned 0x44520010.
            cout << colliders[c]->GetPosition().x << endl;
        }
    }
}

您的问题在这里:

collidersByLayer[layer].push_back(&collider);

您将指针添加到该集合的本地变量。当AddCollider返回时,该对象被破坏。

问题是在collidersByLayer[layer].push_back(&collider);线上,您将Collider collider的地址(是本地对象)推入静态映射。每当范围属于终点时,本地物体就会被破坏。换句话说,一旦函数返回,该指针就指向被破坏的对象。如果您再次致电AddCollider,您将尝试从不确定行为的悬挂指针中读取。

听起来像Collider对象已经存在,您只想将其地址添加到地图中。在这种情况下,您可以简单地将函数的参数作为参考类型。通过这样做,您将获得引用对象的地址,而不是这些对象的本地副本的地址。尝试以下内容:

void AddCollider(Collider & collider, int layer)