Boost logo

Boost Users :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-04-25 18:31:52


On Thursday 25 April 2002 07:09 pm, you wrote:
> Why does the operator == function in the shared_ptr class compare the
> pointer values and not what they are pointing to?

This is the behavior of C++ pointers, and it would be more confusing if
shared_ptr's had different comparison behavior. If there were a
shared_reference class, then I would expect operator== to compare the
referenced objects (as is done with C++ references).

> I'm trying to use the find function (in the stl) and I don't know how to
> get around this. Here's an example.
>
> vector <shared_ptr <SomeClass> > vecStuff;
> shared_ptr<SomeClass> pkToFind(new SomeClass(x,y,z));
>
> if (find(vecStuff.begin(), vecStuff.end(), pkToFind) != vecStuff.end())
> {
>
> }
>
> This didn't work as expected because the shared_ptr class's operator==
> function does not use SomeClass's operator == function to do the
> comparison. Instead it compares the pointer values. I don't understand why
> they made it like this and I don't think they were dumb enough to overlook
> this so there must be something I'm missing.

One way to solve this is to create a function object that dereferences the
pointers and compares the objects they point to. Then you can use that
function object with find_if:

class SomeClassPtrsEqual {
public:
  SomeClassPtrsEqual(const shared_ptr<SomeClass>& p) : ptr(p) {}

  bool operator()(const shared_ptr<SomeClass>& other) const
  {
    return *other == *ptr;
  }

private:
  shared_ptr<SomeClass> ptr;
};

Your code would then become:

vector <shared_ptr <SomeClass> > vecStuff;
SomeClassPtrsEqual isPk(new SomeClass(x,y,z));

if (find_if(vecStuff.begin(), vecStuff.end(), isPk) != vecStuff.end())
{

}

        Doug


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net