Search code examples
c++qtboostoperator-overloadingshared-ptr

Boost shared_ptr seems doesn't support operator ==


Here is the that runs on the latest QT IDE under Windows 7 (boost.1.48)

class Employee {
public:
    int Id;
...
bool operator==(const Employee& other) {
       qDebug() << this->Id << ":" << "compare with " << other.Id;
       return this->Id==other.Id;
   }
}

testing code:

Employee jack1;
jack1 == jack1;   // the operator== gets invoked.

shared_ptr<Employee>  jack(new Employee);
jack == jack;  //  the operator== doesn't get invoked.

The related code in the boost header file is:

template<class T, class U> inline bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b)
{
        return a.get() == b.get();
}

It seems that it is doing the pointer compare instead of doing the what I expect it.

What do I do wrong?


Solution

  • shared_ptr is a pointer-like class (it models a pointer with extra features) so operator== for shared_ptr compares pointers.

    If you want to compare the pointed-to objects you should use *jack == *jack, just like normal pointers.