首页 > 解决方案 > 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:
enter image description here

And, from debugger mode, I have this: - first iteration enter image description here

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.

标签: c++pointersvectordestructor

解决方案


推荐阅读