简体   繁体   中英

c++ pathfinder - vector of objects with pointers

I have a problem with destructor. I have two classes: Map and Tile. They looks like that: (if code fragments below are not enough i'm adding github with this project with full code inside: https://github.com/TMalicki/PathFinder-algorithms )

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();
...
}

They destructors looks like that:

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: Map object has vector of Tiles. And every Tile firstly is not pointing anything. But if it's used by algorithm than this exact Tile store position of previous one, and so on to the beginning. I know propably smart pointers can help me but i though it would be good for me to learn firstly how to do this maybe harder way. I think that the problem is that (i don;t exactly know why) while deleting Map vector with Tiles i do not only delete exact Tile, but also somehow Tile who is parent of that Tile? And fe in the next iteration when it should delete that parent of previous iteration it cannot because it is already delete. I thought that after if statement inside Tile destructor it wont be delated if it already is. But it's not helping.

I've got exception thrown like that:
在此处输入图片说明

And from debugger mode i have this:

  • first iteration
    在此处输入图片说明

  • second iteration
    在此处输入图片说明

During analisation from debugger mode i've start thinking that destructor of exact tile delete firstly parent tile, and than himself. And after that it jumps to line parent = nullptr inside Tile destructor. But somehow only child Tile is being set to nullptr.

The problem is likely that parent is not an owning pointer so it should not delete the parent.

Tile::~Tile() {
    if (parent != nullptr) {
        delete parent; <----------- here
        parent = nullptr;
    }
}

Otherwise when Map delete the tile, it has already been deleted. Removing this part of the code should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM