问题描述
我正在用C ++和SFML制作游戏,并且在用数组渲染各种项目时遇到问题。当我尝试绘制一个精灵数组时,调试正常,没有警告和错误,但是我的游戏程序仅运行20秒,然后停止运行,并说:“ 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类正在进行浅表复制。这意味着,如果Sprite类使用new
运算符分配任何内存并将其存储在成员指针中,则浅表副本将仅复制指针指向的地址。当您确实调用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>
;