Should I loop through tiles and delete each one? Or is there a better way?

  if(tiles->at(i) != NULL) delete tiles->at(i);

   std::vector<Tile*> tiles;


    //TODO: need to fix this to match sprite sheet tiles size
   for (int y = 0; y < 10; y++) {
      for (int x = 0; x < 32; x++) {
         tiles.push_back((new Tile(x * 32, y * 32, 32, 32)));
      }
   }


class Tile {
public:
   Tile(int left, int top, int w, int h);
   Tile(int left, int top, int w, int h, bool solid);
   virtual ~Tile();
   bool isSolid();
   sf::IntRect getTileRect();
private:
   sf::IntRect tileRect;
   bool solid;
};

#endif  /* TILE_H */


#include "Tile.h"

Tile::Tile(int left, int top, int w, int h) {
   tileRect.left = left;
   tileRect.top = top;
   tileRect.height = h;
   tileRect.width = w;
   solid = false;
}

Tile::Tile(int left, int top, int w, int h, bool solid) {
   tileRect.left = left;
   tileRect.top = top;
   tileRect.height = h;
   tileRect.width = w;
}

bool Tile::isSolid() {
   return solid;
}

sf::IntRect Tile::getTileRect() {
   return tileRect;
}

Tile::~Tile() {
}

Recommended Answers

All 3 Replies

Should I loop through tiles and delete each one? Or is there a better way?

Yes, and. :) With your current setup, you have little choice but to loop through the vector and delete each pointer. However, a better setup would be to use smart pointers (shared_ptr or unique_ptr) from the get go.

Thanks, I will look into them. I'm learning as I go, so I will do a google search for some articles on both of those.

Here, take a look at this simple example, maybe it will help you understand how smart pointers can work:

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

#define SIZE 10

class Test 
{
    int* nr, curElem;
public:
    Test()
    {
        cout<<"Object created\n";
        nr = new int [SIZE];
        curElem = 0;
    }

    bool Add(int element)
    {
        if (curElem == SIZE) return false;
        cout<<"Element added: "<<element<<"\n";
        nr[curElem++] = element;
        return true;
    }

    ~Test()
    {
        cout<<"Destructor called.\n";
        delete [] nr;
    }
};

int main()
{
    vector<unique_ptr<Test>> test;
    for (int i=0;i<5;i++){
        unique_ptr<Test> obj(new Test());
        int j = 0;
        while (obj.get()->Add(j++));
        test.push_back(move(obj)); //move the smart pointer into the vector container
    }
    return 0;
}

And here is a very well written post regarding smart pointers:
Click Here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.