While I do understand why there is no operator==
for shared_ptr
and unique_ptr
, I wonder why there is none for shared_ptr
and weak_ptr
. Especially since you can create a weak_ptr
via a reference on shared_ptr
.
I would assume that for 99% of the time you want lhs.get() == rhs.get()
. I would now go forward and introduce that into my code unless someone can name me a good reason, why one should not do such a thing.
weak_ptr
doesn' have a get()
method because you need to explicitly lock the weak_ptr
before you can access the underlying pointer. Making this explicit is a deliberate design decision. If the conversion were implicit it would be very easy to write code that would be unsafe if the last shared_ptr
to the object were to be destroyed while the underlying pointer obtained from the weak_ptr
was still being examined.
This boost page has a good description of the pitfalls and why weak_ptr
has such a limited interface.
If you need to do a quick comparison, then you can do shared == weak.lock()
. If the comparison is true then you know that weak
must still be valid as you hold a separate shared_ptr
to the same object. There is no such guarantee if the comparison returns false.