Question

I have two QSharedPointer, can I check are they pointed to the same object using operator== like this

QSharedPointer1 == QSharedPointer2

or I must write

QSharedPointer1.data() == QSharedPointer2.data()

Object that are stored in pointers have overloaded operator==.

Was it helpful?

Solution 2

From the QSharedPointer class reference:

bool operator==(const QSharedPointer<T>& ptr1, const QSharedPointer<X>& ptr2)

Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2.

OTHER TIPS

You should use operator==:

bool operator== ( const QSharedPointer & ptr1, const QSharedPointer & ptr2 )

Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2. If ptr2's template parameter is different from ptr1's, QSharedPointer will attempt to perform an automatic static_cast to ensure that the pointers being compared are equal. If ptr2's template parameter is not a base or a derived type from ptr1's, you will get a compiler error.

So, there is no need to fetch the pointers via data() method, + it will try to do static_cast to match the template arguments.

Also, note that it doesn't matter if objects stored in the pointer have overloaded operator== - you are just comparing pointers here, and operator== is defined for pointer types. If you want to compare the objects which pointers are referring to, you need to dereference pointers and to compare references to the objects (which will call T::operator== method):

if(*ptr1 == *ptr2)
   // ...

first version should be OK related to here

bool operator== ( const QSharedPointer<T> & ptr1, const QSharedPointer<X> & ptr2 )

Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top