Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing equality between shared_ptr and weak_ptr

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.

like image 863
abergmeier Avatar asked Jun 10 '12 11:06

abergmeier


2 Answers

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.

like image 168
CB Bailey Avatar answered Sep 22 '22 02:09

CB Bailey


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.

like image 30
Matthieu M. Avatar answered Sep 22 '22 02:09

Matthieu M.