c++ - c++ vector of objects with pointer destructor
问题描述
I have a problem with destructor. I have two classes: Map
and Tile
. They look like this:
class Tile
{
private:
Tile* parent;
...
public:
Tile(sf::Vector2f size = { 50.f ,50.f });
Tile(const Tile& cTile);
Tile& operator=(const Tile& aTile);
~Tile();
...
}
and
class Map
{
private:
vector<Tile*> board;
...
public:
Map(sf::Vector2i numberOfTiles = { 10, 10 }, sf::Vector2f sizeOfTiles = {
50.f, 50.f });
Map(const Map& cMap);
Map& operator=(const Map& aMap);
~Map();
...
}
Their destructors looks like this:
Tile::~Tile()
{
if (parent != nullptr)
{
delete parent;
parent = nullptr;
}
}
Map::~Map()
{
for (int i = 0; i < board.size(); i++)
{
delete board[i];
board[i] = nullptr;
}
}
Code is used for shortest path search algorithm. I have to store previous Tile
so when algorithm find finish it can search backwards shortest path. I can add some more code if it's needed. To sum up: a Map
object has a vector of Tiles
, and every Tile
is initially not pointing to anything. But, if it's used by algorithm than this exact Tile
stores the position of previous one, and so on to the beginning. I know that smart pointers can probably help me but I thought it would be good for me to learn first how to do this maybe the harder way.
I think that the problem is that (I don't exactly know why) while deleting the Map
vector with Tiles
I not only delete the exact Tile
, but also somehow the Tile
who is parent of that Tile
? And, for example, in the next iteration, when it should delete that parent of previous iteration, it cannot because it is already deleted.
I thought that, after the if
statement inside the Tile
destructor, it won't be deleted if it already is. But it's not helping.
I've got exception thrown like this:
And, from debugger mode, I have this: - first iteration
During analysis from debugger mode, I've start thinking that the destructor of exact Tile
deletes first parent Tile
, and than himself. And after that it jumps to the line parent = nullptr
inside the Tile
destructor. But somehow only the child Tile
is being set to nullptr
.
解决方案
推荐阅读
- python - 如何将值从列复制到postgresql中不存在的列
- excel-formula - 条件格式:如果单元格包含来自另一列的部分文本,则需要突出显示该单元格
- oauth-2.0 - 如何在 oAuth 2.0 中存储和使用访问令牌和刷新令牌以保持用户的登录状态?(吉拉 OAuth 2.0)
- python - Pandas DataFrame 基于依赖于具有累积计数规则的其他列的逻辑创建新列
- android - Android:如何从相机获取原始图像数据
- node.js - 将 pdf 转换为图像不适用于 Windows 上的 Nodejs sharp
- single-sign-on - 当我们在 MS Edge 中启用 IE 模式时,ADFS SSO 失败
- bash - zsh 和 bashrc 命令未找到 ts-node
- apache-spark - 检查每个 RDD spark 内部的数据
- stm32 - 如何使用 HAL_I2C_Transmit?