0

So I have a class which has an id data member and I'm using it in a QList<QSharedPointer<MyClass>> and I'm unsure about how to go about checking to see if there's an existing id in that QList. How would I go about doing that exactly as QList::contains would require a QSharedPointer<MyClass>& rather than a MyClass*

Should I just use a QHash which uses the id as the key?

Hcorg
  • 11,598
  • 3
  • 31
  • 36
SuperWig
  • 155
  • 3
  • 14
  • Choosing what container to use - it's your decision. To choose, what container to use you should know about algorithm complexity for each operation that container provides. – Dmitry Sazonov Oct 16 '15 at 08:25
  • If your software runs to a case where you get raw MyClass* and in other situation it is hold by QSharedPointer than definetly you have something wrong with your design. Whole idea of QSharedPointer is to pass object always as QSharedPointer. Otherwise it may happen that you have invalid pointer in your code – Kamil Klimek Oct 16 '15 at 09:43
  • @KamilKlimek Sorry what I meant by that was that if I wasn't using a QSharedPointer I would just write an operator overload which should then work with `contains` – SuperWig Oct 16 '15 at 09:59
  • You can't override operator== for poitner type – Kamil Klimek Oct 16 '15 at 11:47

1 Answers1

1

QList::contains algorithm is based on == operator. As is stated in Qt documentation the == operator of QSharedPointer returns true if the values of the two managed raw pointers have the same value.

Also if you had been used raw pointers in QList it would not work because you can not overwrite the == operator of the raw pointer (you have pointers to MyObject in the list not objects so the overloaded == of MyObject will not been called).

The only solution is to manually iterate the list and check for equality using a for loop.

demonplus
  • 5,613
  • 12
  • 49
  • 68
Ilie NEACSU
  • 530
  • 3
  • 12
  • For some reason I assumed that it would call the correct `==` if it contained `MyClass*`. Though I figured I would just end up creating my own check with `std::find_if` if this was the case. Thanks for your answer. – SuperWig Oct 16 '15 at 19:36