If I have a shared_ptr that I copy into a std::thread, detach the thread, and then I destroy all other copies of the shared_ptr, can I expect the detached thread to continue to have a live copy of the shared_ptr? For example if I have:
{
std::shared_ptr<Foo> my_foo = std::make_shared<Foo>();
std::thread soon_detached([my_foo = my_foo]() {my_foo->bar()});
soon_detached.detach();
}
Can I trust that bar()
is "safe" to call in that situation (in that it won't try to call bar on a Foo that's being destructed/is destructed even if the initial copy of my_foo
is long out of scope?
Does a detached thread keep its captured shared_ptr alive?
Yes. The lambda - and thus also the captures of the lambda - will stay alive as long as the thread is executing. Same would also apply to args
passed into std::thread
.
we're deleting our own handle to the std::thread at the end of the scope
The std::thread
object won't contain the functor. It will need to be stored in dynamic memory. The lifetime of the executing thread is separate from the lifetime of the std::thread
wrapper.