There is a problem with this question.
- Thread 1 has a
std::shared_ptr<int> sptr
- ok.
- Thread 1 returns,
sptr
goes out of scope - ok.
- This causes the object held by
sptr
to be destroyed - ok, but this means that there are no other copies of sptr
anywhere, or they would have kept the contained object alive.
- Thread 2 copies
sptr
- from where? We just agreed that the last copy of the shared pointer went out of scope, that means that there is nowhere for thread 2 to copy it from.
So there is something wrong with the premise of your question.
You may be tempted to say: "Oh, but I has a pointer to sptr
, and thread 2 tried to copy it through that", the answer to that is that you should not have pointers (or references) to shared pointers. The entire point of their existence is that you pass them by value - if you fail to do that, then you violate the contract and they no longer guarantee safety.
Now, it is occasionally the right choice to pass a pointer (most commonly to the contained object) to some function that can't use shared pointers (often old C-style APIs). BUT! Be aware that when you do so, you assume the full responsibility for maintaining the lifetime of the shared pointer and its contained object for as long as that raw pointer is in use.