1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"the behavior of lock() is as this code, but atomically with regard to other threads." If so, the standard text says nothing, and thus is defective.
@R.MartinhoFernandes: The standard doesn't define the implementation, but the value of the result. So the standard text is fine.
@R.MartinhoFernandes: On second thought, I recall the atomicity of weak_ptr::lock() from boost, but now I'm not sure if this applies to the libstd implementation. This and maybe this seem to suggest that they do, but I now cannot find confirmation in the standard...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.