std::thread stores its supplied arguments and invokes the thread function with those stored values as rvalues. Use std::ref when the function needs a non-const reference to the original object. section 2.2
Choose how each argument reaches the new thread:
- Wrap an lvalue in std::ref to pass it by reference; ensure it remains alive until the thread has finished. section 2.2
- Pass an owning std::string rather than a pointer to a local buffer when detaching a thread. section 2.2
- Use std::move to transfer a move-only argument such as std::unique_ptr; member-function calls take the object pointer first. section 2.2
std::thread t(update_data_for_widget,w,std::ref(data));
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":39},{\"line\":0,\"ch\":53}]]"}
!@%STYLE%@!
See the std::ref change that passes the original data object to the thread function. section 2.2
void process_big_object(std::unique_ptr<big_object>); std::unique_ptr<big_object> p(new big_object); p->prepare_data(42); std::thread t(process_big_object,std::move(p));
See a unique_ptr moved into a thread function. section 2.2
