Вопрос

I have a problem with sorting. I sort the objects containing the dynamic table. It seems that the stable_sort (or the vector) doesn't use a public copy constructor. I looks like they use a non-existent constructor with no parameter because the tables inside the objects are freed - I think.

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

class Dynamic{
  int n;
  int *tab;
public:
  int getN() const{ return n;}
  int *getTab() const {return tab;}
  Dynamic(int ile){
    n=ile;
    tab=new int[n];
    for(int i=0; i<n; i++)
      tab[i] = (10-i)%10;
  }
  Dynamic(const Dynamic& d){
    n = d.getN();
    tab = new int[n];
    for(int i=0; i<n; i++)
    tab[i] = d.getTab()[i];
  }
  bool operator<(const Dynamic& a) const{
    return n < a.getN();
  }
  ~Dynamic(){
    delete[] tab;
  }
};
int test(vector<Dynamic> & c){
  vector<Dynamic> d(c);
  stable_sort(d.begin(), d.end());
  d.clear();
}
int main(){
  vector<Dynamic> c;
  c.push_back(Dynamic(15));
  test(c);
  cout<<"test!";
  return 0; 
}

STL's sort is also affected but in slightly more complex way. In g++-4.7.2 I can compile this and in running I get "double free or corruption (fasttop)"/core dumped (full report isn't helpful, I think). On online g++-4.9.0 it looks similar: "No output: Error: stdout maxBuffer exceeded.".

Where is my mistake? Thank you for your attention.

Это было полезно?

Решение

Well, you didn't overload the operator= for Dynamic, so the compiler implicitly defines one which would do bitwise copy. stable_sort() in your library calls the operator=, so tab in two Dynamic objects points to the same address, as a result, double delete on destruction. Overloading the operator= would resolve the problem:

Dynamic& operator =(const Dynamic& d)
{
     // or use the copy-and-swap idiom
     if(this != &d)
     {
         delete [] tab;
         n = d.getN();
         tab = new int[n];
         for (int i = 0; i<n; i++)
             tab[i] = d.getTab()[i];
     }

     return *this;
 }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top