0
votes

I'm writing a program for my friends during my summer time and I occurred really strange problem.

I'm assigning a QVector< T > to other QVector< T > with operator= in my homemade template class and then trying to check whethere this 2nd QVector< T > have any elements. First, I'm checking it's size and it's good, but when I use operator[] and function GetName() which is a member of class T.

Here's some code:

 template <template T> class Turniej {
 private:
  QVector<T>* list_;
  QVector<Stol<T> > stoly_;
  int round_;
  int max_rounds_;
  Turniej() {round_=1;}
 public:
  static Turniej& GetTurniej() {
   static Turniej turniej;
   return turniej; }
  void SetList(QVector<T> *list) {list_=list; }
  QVector<T>& GetList() {return *list_;}
  //Some other irrelevant methods
 };

Then I invoke SetList() function with reference to QVector filled with 2 objects of Gracz class

  Turniej<Gracz>::GetTurniej().SetList(&list)

And when I'm finally trying to get to the list_ object in Turniej class by code below, I get this error: ASSERT failure in QVector::operator[]: "index out of range", file .../QtCore/qvector.h, line 356

 qDebug()<<Turniej<Gracz>::GetTurniej().GetList()[0].GetName();

Where GetName() returns some QString and for certain that method exists in Gracz class.

I would really appreciate any help, because I'm stuck with it for 2 days and have completely no idea what's going on. What is strange, I was trying to google that error but I haven't found any topic with error in that particular line of qvector.h. I'm using Qt 5.0.2 with Qt Creator

Thanks for any help!

2
Why are you dealing with QVector by pointer? My guess is that the pointer is invalid by the time you access it. Just use a plain QVector.Sebastian Redl
returning the reference to a dereferenced pointer is a bad idea, you could dereference a NULL or uninitialized pointer!!!WoJo
I did changed pointers to plain QVectors and tried to use operator= in SetList() function by list_=list and still the sameTheoden91

2 Answers

0
votes

when you call SetList, you are transferring the ownership of the list, are you shure you are not deleting it (or it is not getting deleted automatically) afterwards?

0
votes

Change list_=list; to list_ = new QVector(list). Maybe your vector is modified somewhere outside of your class? You're just keeping reference to vector given to your method, it seems like copying is what you want.

updated
I see your class is a singleton. Always remember to think twice before making a class a singleton - it's not a thing you want to have in your code, and it should be avoided when possible.