gpt4 book ai didi

执行指针时出现 C++ 访问冲突

转载 作者:行者123 更新时间:2023-11-28 04:55:59 25 4
gpt4 key购买 nike

我正在使用 C++ 和 sfml 开发一款游戏,其中我有小行星从屏幕上掉下来,玩家发射激光来摧毁它们。当小行星或激光离开屏幕时,它们将从各自的 std::vectors 中删除和删除:

小行星:

std::vector<Asteroid*>::iterator it;
for (it = asteroids.begin(); it < asteroids.end(); ) {
(*it)->update(dt);

if ((*it)->getPosition().y > Game::window.getSize().y) {
delete * it;
asteroids.erase(it);
}
else {
it++;
}
}

激光:

for (int i = 0; i < lasers.size(); i++) {
lasers.at(i)->update(dt);

if (lasers.at(i)->getPosition().y < 0) {
delete lasers.at(i);
lasers.erase(lasers.begin() + i);
i--;
}
}

当我尝试检测它们之间的碰撞时,问题就来了。我遍历每个激光实例中的所有小行星,并使用父类 GameObject 中的方法检查它们之间的碰撞。

for (int i = 0; i < Game::spawner->asteroids.size() - 1; i++) {

if (isColliding(asteroids.at(0))) { // Access violation executing location 0x071DE528.
printf("collided");
//delete asteroids.at(i);
//asteroids.erase(asteroids.begin() + i);
break;
}
}

这是 isColliding 和 getPosition 方法:

bool GameObject::isColliding(GameObject * g) {

sf::Vector2f gPos = g->getPosition();
sf::Vector2f pos = this->getPosition(); // after waiting a few seconds and then testing the collision, I get this error here: Access violation executing location 0x00000000.



if (gPos.x <= pos.x && pos.x <= gPos.x + g->width
|| pos.x <= gPos.x && gPos.x <= pos.x + width) {

if (gPos.y <= pos.y && pos.y <= gPos.y + g->height
|| pos.y <= gPos.y && gPos.y <= pos.y + height) {

return true;
}
}
return false;

sf::Vector2f GameObject::getPosition() {

if (isLoaded) {
if (animated)
return animatedSprite.getPosition();
else
return sprite.getPosition(); // the asteroids are not animated, so this will be called.

}

我在这上面花了几个小时,但我似乎无法弄清楚发生了什么。我想我正在安全地删除指针和它们的索引,所以我不知道从那里去哪里。作为引用,isColliding 函数确实适用于两个不同的游戏对象(玩家和小行星)。这个问题似乎与遍历所有小行星有某种关系。

感谢您的帮助。

更新的小行星删除:

int toDelete = -1;
for (int i = 0; i < asteroids.size(); i++) {
asteroids.at(i)->update(dt);

if (asteroids.at(i)->getPosition().y > Game::window.getSize().y) {
toDelete = i;
}
}

if (toDelete != -1) {
delete asteroids.at(toDelete);
asteroids.erase(asteroids.begin() + toDelete);
}

最佳答案

您正在使用迭代器遍历小行星然后删除它们,但是文档指出在调用 erase 之后迭代器将失效:

Erase documentation

Iterators, pointers and references pointing to position (or first) and beyond are invalidated, with all iterators, pointers and references to elements before position (or first) are guaranteed to keep referring to the same elements they were referring to before the call.

因此,在第一次调用删除后,您的指针不再有效,任何事情都可能发生。尝试另一种删除策略,例如首先识别注定要消失的小行星,然后分别将它们删除。

关于执行指针时出现 C++ 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47123770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com