c++qtpointersqsharedpointer

Comparison of pointers QSharedPointer<T> and T*


I am trying to compare a QSharedPointer with a raw pointer to the underlying object:

MyClass* object = new MyClass;
QSharedPointer<MyClass> sharedObject (object);

if(object == sharedObject)
   return true; // If Equal

Will this work correctly?


Solution

  • Yes it is valid, because QSharedPointer has a related operator==:

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

    That compares a raw pointer to a QSharedPointer and:

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

    So in your case (object == sharedObject) will be true.

    Note:
    The operands can also be compared in the opposite order, because there is also:
    template <typename T, typename X> bool operator==(const QSharedPointer<T> &ptr1, const X *ptr2).