gpt4 book ai didi

c++ - 如何在没有内存泄漏的情况下删除对象指针的二维 vector ? C++ 和 SFML

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:39 25 4
gpt4 key购买 nike

我有一个 2D vector 的 Tile 指针。每次加载不同的 map 时,我都想删除 vector 中的所有 Tiles,释放内存,然后用不同的 tiles 重新填充它。

std::vector<std::vector<Tile*>> map;

这是我的 Tile 类:

#ifndef _TILE_H
#define _TILE_H

#include <SFML\Graphics.hpp>

class Tile
{

public:
int type;
int color;
int light_level;
int loc_x, loc_y;

Tile();
~Tile();

sf::Sprite baseSprite;

void Draw(int x, int y, sf::RenderWindow* rw);

void setTexture(sf::Texture& texture);
};

#endif

我像这样填充 vector :

map[x][y] = tile;

问题是,每次我用 Tiles 重新填充 vector 时,我的内存都会继续填满,直到游戏崩溃。我的问题是,如何正确删除 vector 中的所有内容以释放内存?

这是我尝试删除未释放内存的图 block 的尝试:

for(int ii = 0; ii < this->map.size(); ii++){
for(int jj = 0; jj < this->h; jj++){

delete &this->map[ii][jj]->baseSprite;
delete &this->map[ii][jj]->color;
delete &this->map[ii][jj]->light_level;
delete &this->map[ii][jj]->loc_x;
delete &this->map[ii][jj]->loc_y;
delete &this->map[ii][jj]->type;

delete &this->map[ii][jj];
}
}


map.clear()

如果需要任何额外的代码,请告诉我,谢谢。

最佳答案

Tile来看类,使用 Tile 似乎很愚蠢指针而不是直接使用 Tile s 在你的 vector 中。以下是您的问题的可能解决方案:

  1. 定义一个复制构造函数,即定义Tile::Tile(const Tile&)应该做的(它应该将所有数据成员复制到新构造的图 block 中)。
  2. 定义一个赋值运算符,即定义什么Tile& Tile::operator=(const Tile&)应该做的(它应该在其所有数据成员和 operator= 上调用所有 return *this 函数)。

现在乍一看这似乎没问题,但我查看了 sf::Sprite文档,并且没有为 sf::Sprite 定义复制构造函数和赋值运算符.看起来 Sprite 只能通过 sf::Texture 创建.幸运的是,每个 sf::Sprite公开一个返回其自身绑定(bind)的公共(public)成员函数 sf::Texture .但是,查看 sf::Sprite::getTexture() 的文档,它返回一个指向 sf::Texture指针 ,可能是 NULL如果还没有纹理绑定(bind)到 sf::Sprite .您应该在 Tile 的复制构造函数和赋值运算符中检查它.

复制构造函数应该看起来像这样:

Tile::Tile(const Tile& other)
: type(other.type)
, color(other.color)
, light_level(other.light_level)
, loc_x(other.loc_x)
, loc_y(other.loc_y)
, baseSprite()
{
sf::Texture* result = other.baseSprite.getTexture();
if (result)
{
baseSprite.setTexture(*result);
}
}

赋值运算符应该是这样的:

Tile& Tile::operator = (const Tile& other)
{
type = other.type;
color = other.color;
light_level = other.light_level;
loc_x = other.loc_x;
loc_y = other.loc_y;
sf::Texture* result = other.baseSprite.getTexture();
if (result)
{
baseSprite.setTexture(*result);
}
return *this;
}

不过还有更多,它似乎是一个 sf::Sprite也可以由纹理的子矩形定义,并且它可能有更多您需要注意的属性。例如,sf::Sprite还有它的位置、旋转、全局颜色的 getter 和 setter,所有这些你都需要复制。无论如何,一旦完成,您就可以忘记指针困惑并实例化

std::vector<std::vector<Tile> >

相反。

关于c++ - 如何在没有内存泄漏的情况下删除对象指针的二维 vector ? C++ 和 SFML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24087416/

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