Question

std says:

shared_ptr<T> lock() const noexcept;

Returns:

expired() ? shared_ptr<T>() : shared_ptr<T>(*this).

but in between expired returning false (the object still exists) and the construction of the shared_ptr another thread could remove the last strong reference, thus throwing an unexpected exception? how to prevent this?

or do i miss something?

Was it helpful?

Solution

You don't have to prevent it, it is taken care of by the implementation of the standard library.

The cited code is for illustration purposes only: the behavior of lock() is as this code, but atomically with regard to other threads.

If you want to know how it is done, you can peek the source code. It is a template class, so the code will surely be in the header files. But beware! The standard C++ library source code is not for the faint of heart.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top