I think you have it correctly. This is not really specific to "threads" as such, but more to the behaviour of unique_ptr
which destroys its owned pointer when it goes out of scope. In your example, you could replace Thread
with Banana
and MyRunner
with Apple
and the behaviour in that sense would be the same.
Thanks. Then if I want to start 50 threads in a loop, and still use smart pointers to control the thread objects, how can I modify the above code? (is there a way to let the threads keep running even if their controlling smart pointers going out of scope)?
So far as threads are concerned, they will continue running regardless of whether the smart pointers have died or not. A better question might be to see how you can keep the smart pointers alive until the threads have finished running. To do this, you would need to know two things, the first being, how do you know when a thread has completed processing, and the second, how to keep a reference to multiple smart pointers.
To answer the first part would depend on the details of your underlying threading implementation so I can't speak to that in too much detail.
For the second, probably an array such as std::vector is going to be useful. You might like to refer to these questions for information on possible pitfalls of this approach:
So can unique_ptr be used safely in stl collections?
Why can I not push_back a unique_ptr into a vector?