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?

billz
  • 44,644
  • 9
  • 83
  • 100
Klaus Ahrens
  • 229
  • 3
  • 7

1 Answers1

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.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • "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. Martinho Fernandes Jun 27 '13 at 12:14
  • 2
    @R.MartinhoFernandes: The standard doesn't define the implementation, but the *value* of the result. So the standard text is fine. – Kerrek SB Jun 27 '13 at 12:16
  • @R.MartinhoFernandes: On second thought, I recall the atomicity of `weak_ptr::lock()` from [boost](http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/weak_ptr.htm), but now I'm not sure if this applies to the libstd implementation. [This](http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html) and maybe [this](http://msdn.microsoft.com/en-us/library/c9ceah3b%28v=vs.100%29.aspx) seem to suggest that they do, but I now cannot find confirmation in the standard... – rodrigo Jun 27 '13 at 13:58