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
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