抛出例外:阅读访问违规.访问数组中的指针时
Exception thrown: read access violation. when accessing pointer in array
我在尝试调用存储在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)
相关文章:
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 从数组访问SDL_Rect成员时垃圾值?
- 从 C++ 中的 int ** 数组访问元素
- 使用动态数组访问冲突写入位置
- 如何使用对象数组访问类中的变量?
- 从链表数组访问节点数据
- 返回类型的数组访问
- 在 C++ 中使用指针的数组:访问返回的数组时出现分段错误
- 为什么2D数组访问要比1D阵列访问更快
- 指向数组访问的指针上的隔离错误
- C 通过对象的指针数组访问对象方法
- C 通过数组访问多个成员
- C++可变参数模板数组/访问元素
- 数组访问导致空指针取消引用
- 无法从类数组访问数组
- 为什么编译器允许越界数组访问,即使使用 constexpr 索引也是如此
- C++ 从数组访问重载构造函数
- 为什么为了简单的数组访问,我必须在g++中打开优化
- 如何在重载数组访问运算符时访问SIMD矢量元素
- C++大型2D数组访问冲突