c++ - C++ SFML 数组错误:访问冲突读取位置 0xC0000005
问题描述
我正在使用 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];
and only the std::vector<Sprite> items;
,像这样:
std::vector<Sprite> items;
items.push_back(bomb);
items.push_back(coffee);
...
window.draw(items[i]);
您不需要使用中间数组,只需std::vector<Sprite>
;
推荐阅读
- groovy - Groovy 'with' 方法的意外行为 - 变量分配静默失败
- php - 使用 PHP 和 AJAX 将数据库中的值填充到表中
- java - 如何在jsonObject中的数组中获取某些元素
- c# - 使用 JToken 时保留的内存
- r - sparklyr spark_read_parquet 来自 s3 错误
- python - 当nodejs产生子进程时python找不到pip安装的库
- c# - 对象列表
在 RAM 上占用太多内存 - multithreading - 你如何在颤动的另一个线程上运行操作?
- django - How to provide autocomplete street addresses functionality in django?
- reactjs - 根据下拉菜单中的对象选择更新状态