Question

I'm reading the Boost documentation for weak_ptr here and in the beginning it says:

When the last shared_ptr to the object goes away and the object is deleted, the attempt to obtain a shared_ptr from the weak_ptr instances that refer to the deleted object will fail: the constructor will throw an exception of type boost::bad_weak_ptr, and weak_ptr::lock will return an empty shared_ptr.

Everything clear so far, however, 2 lines later it says:

weak_ptr operations never throw exceptions.

What does each statement refer to?

Was it helpful?

Solution

The weak_ptr class never throws on any operation, internally, what happens when you call lock() is that it catches the exception thrown by the constructor of the shared_ptr (bad_weak_ptr) and then returns you an empty shared_ptr. Have a look at the source of the lock() function for yourself to confirm.

OTHER TIPS

Constructing a shared_ptr from a weak_ptr may throw an bad_weak_ptr exception. (Use weak_ptr::lock instead, if you want to be able to test for this.)

Any operations on a weak_ptr object itself will not throw.

It means that if you construct a shared_ptr (template<class Y> explicit shared_ptr(weak_ptr<Y> const & r); ) from a weak_ptr when the shared instance referenced by the weak_ptr is gone, it will throw an exception.

You have two ways to obtain shared_ptr from weak_ptr :

  • shared_ptr constructor, it will throw if the instance referenced by the weak_ptr is gone
  • shared_ptr<T> weak_ptr<T>::lock() const; it will return an empty instance of shared_ptr if the instance referenced by the weak_ptr is gone.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top