Search code examples
c++qtqlistqsharedpointer

QList::contains with a QSharedPointer


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?


Solution

  • 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.