简体   繁体   中英

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?

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.

try this:

(*jack) == (*jack);

Remember to deference your pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM