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.
Because it has a cost.
A weak_ptr
is like an observer, not a real pointer. To do any work with it you first need to obtain a shared_ptr
from it using its lock()
method.
This has the effect of acquiring ownership, but it as costly as copying a regular shared_ptr
(count increment, etc...) so it is nothing trivial.
As such, by not providing ==
, you are forced to step back and actually check whether you really need this or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With