[英]C++ SFML Array Error: Access violation reading location 0xC0000005
我正在使用 C++ 和 SFML 制作游戏,并且在使用数组渲染各种项目时遇到问题。 当我尝试绘制一组精灵时,调试正常,没有警告和错误,但我的游戏程序只运行了 20 秒,然后它停止运行,并说,'Unhandled exception at 0x7C50CF2E(sfml-graphics- d-2.dll),ECOVID-19 SFML.exe):0xC0000005:访问冲突读取位置 0xCCCCCCD0。 我做了我能做的一切,但我不知道为什么会发生这个异常。 这是我怀疑错误原因的代码。 尽管我的英语很差,但还是感谢您阅读。
#include <SFML/Graphics.hpp>
...
using namespace std;
using namespace sf;
...
int main () {
...
//item Sprites
Texture bombTex;
bombTex.loadFromFile("images/bomb.png");
Sprite bomb;
...
Texture bomb2Tex;
bomb2Tex.loadFromFile("images/bomb_2.png");
Sprite bomb_2;
...
Texture cakeTex;
cakeTex.loadFromFile("images/cake.png");
Sprite cake;
...
Texture coffeeTex;
coffeeTex.loadFromFile("images/coffee.png");
Sprite coffee;
...
Texture chickenTex;
chickenTex.loadFromFile("images/chicken.png");
Sprite chicken;
...
Texture pizzaTex;
pizzaTex.loadFromFile("images/pizza.png");
Sprite pizza;
//item array (I made an item array to display & render various items in the game screen.)
Sprite item[10]; //Although I change the array size to 4 or 5, the same exception occurs.
item[0] = bomb;
item[1] = coffee;
item[2] = bomb_2;
item[3] = chicken;
item[4] = pizza;
std::vector<Sprite> items;
items.push_back(Sprite(item[4]));
...
while (window.isOpen())
{ ...
...
for (size_t i = 0; i < items.size(); i++)
{
if (humanArr[index].getGlobalBounds().intersects(item[i].getGlobalBounds()))
//humanArr[index] is a player Sprite.
{
...
items.erase(items.begin() + i);
}
}
...
window.clear();
...
for (size_t i = 0; i < items.size(); i++)
{
window.draw(item[i]); // <- the exception error occurs here.
}
...
window.display();
}
return 0;
}
可能发生的情况是,当您复制Sprite item[10];
到std::vector<Sprite> items;
Sprite class 正在制作浅拷贝。 这意味着如果 Sprite class 使用new
运算符分配任何 memory 并将其存储在成员指针中,那么浅拷贝只会复制指针指向的地址。 当你调用items.erase(items.begin() + i);
Sprite 的析构函数将被调用,并且在析构函数中它可能在指向某个资源的指针中调用 delete。
当您调用window.draw(item[i]);
图书馆将尝试使用该资源并找到无效地址。
我的建议是不要使用Sprite item[10];
并且只有std::vector<Sprite> items;
, 像这样:
std::vector<Sprite> items;
items.push_back(bomb);
items.push_back(coffee);
...
window.draw(items[i]);
您不需要使用中间数组,只需std::vector<Sprite>
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.