0

Consider the following code:

class Search
{
    List** openList;
    int tam;

    Search(int t)
    {
        tam = t;
        openList = new List*[tam];
        for (int i = 0; i < tam; i++)
        {
            openList [i] = new List();
        }
    }

    virtual ~Search();
}

How should be the correct destructor?

Now, I have this:

Search::~Search() 
{
    for(int i = 0; i < tam; i++) 
    {
        delete openList[i]
    }
    delete[] openList;
}

But, this code breaks my program when I execute this recurrently (sometimes in init and sometimes in destructor) so... it's incorrect.

Any idea?

Thanks you so much :)!

Gala
  • 1
  • 1
  • 3
    The code you show looks OK to me. The problem must be in the code you haven't shown. Though you could save yourself a lot of trouble if you make your `openList` a `std::vector` and forget about explicit heap allocation. – Igor Tandetnik Mar 20 '16 at 19:12

1 Answers1

0

You are violating the rule of three, which is a hallmark of preventing yourself from broken code.

It says that because you have a user defined destructor, you almost certainly need a user defined copy constructor, and a user defined operator=() overload. Let's implement the simplest version of that for your code, which is to ban those transformations:

class Search {
  public:
    Search(int t) {
      tam = t;
      openList = new List*[tam];
      for (int i = 0; i < tam; i++)
      {
        openList [i] = new List();
      }
    }

    virtual ~Search() {
      for(int i = 0; i < tam; i++) 
        delete openList[i]
          delete[] openList;
    }

    Search & operator=(Search const &) = delete;
    Search(Search const &) = delete;

  private:
    List** openList;
    int tam;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173