Reason why somebody would be interested in
//...
new std::thread (func,arg1,arg2);
}
is that std::thread
destructor(unlik
This is not OK according to the final text. Specifically, the destructor of a thread that has been neither join
ed nor detach
ed will call std::terminate
.
std::thread
destructor is not called when the callback returns, but when the thread
object goes out of scope, just like any other object. So, a new
'd thread that is never delete
'd will never be destructed, leaking any associated state (and things potentially going horribly wrong if/when the program terminates with any extra threads still running...)
To answer your question about lifetimes, std::thread
is like std::bind
: it stores copies of its arguments and passes those copies to the callback, regardless of whether the callback takes its arguments by value or by reference. You must explicitly wrap arguments with std::ref
to get reference semantics. In this case, as usual, it's up to you to ensure that no dangling references occur (for instance by calling thread::join()
before any referenced variables go out of scope.)