I can't see how a solution that passes weak pointers would work in the case of multi-threaded code
It works by the combination of these two:
You're locking weak_ptr before use, which creates shared_ptr<> temporarily, so you have guarantee that it won't go away in that scope.
C++11 smart pointers are thread-safe. So sayeth the Standard.
Although the latter is a bit of a "relaxed" wording, it's close enough.
You are explicitly allowed to call all functions including copy constructor of a shared_ptr concurrently and you are guaranteed that the reference counter of a shared_ptr is at all times correct/consistent. That doesn't guarantee that the object still exists when/while you copy the shared pointer, of course. It does guarantee that the result is well-defined, however.
Locking a weak_ptr creates a copy of the shared_ptr which may be an empty shared pointer (if the reference count has gone to zero in the mean time and the object was destroyed). So you have no guarantee that your operation will succeed, but you are guaranteed that the result is verifiable. If the copied shared pointer is nullptr, locking the weak pointer failed and the object is gone. Otherwise you now hold a (temporary) shared_ptr and it's guaranteed that the object will live for as long as you hold the temporary.
Edited by samoth, 09 January 2014 - 10:31 AM.