Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ shared_ptr equality operator

The equality operator for shared_ptr's is defined as follows:

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

This seems broken. Would it not have been better to forward the equality to what a and b are pointing to? Or would that be an unfair restriction on users of the library (in that they have to provide an equality operator) ?

If I have a map or a hash_table containing shared_ptrs, then the current definition makes equality unusable. For example, consider

std::map<int, std::tr1::shared_ptr<T> > m1, m2;

Won't we want to check that the ptrs for each int in m1 and m2 are pointing to the same value ?

I can implement my own equality by flattening m1, m2 out (constructing sets from each, dereferencing shared_ptrs along the way). Is there an STL trick that will accomplish this or some other way to test equality in the presence of shared_ptrs neatly ?

like image 873
user231536 Avatar asked Apr 19 '11 21:04

user231536


1 Answers

It's not broken, because a shared_ptr is conceptually a pointer, therefore it implements pointer-wise equality. When you test two pointers for equality, you want to know whether they point to the same place in memory.

like image 194
Fred Foo Avatar answered Sep 21 '22 01:09

Fred Foo