When attempting to pass a reference to an object, such as a std::ostream, to a thread function, compilation may fail due to a deleted constructor. This issue arises because threads typically copy their arguments to avoid referential aliasing concerns.
To bypass the compilation error, it is essential to utilize std::ref (or std::cref for constant references). std::ref allows you to wrap a reference with value semantics, enabling you to copy the wrapper safely.
std::thread t(foo, std::ref(std::cout));
Here, the std::ref wrapper provides a copyable object that contains the reference to std::cout. Therefore, the thread can successfully copy it and execute the function correctly.
Remember that this code will only function as long as the referenced object remains valid. It is crucial to ensure that the object's lifetime exceeds the execution duration of the thread. Failure to adhere to this may result in undefined behavior.
The above is the detailed content of Why Does Passing Object References to Threads Cause Compilation Errors, and How Can `std::ref` Help?. For more information, please follow other related articles on the PHP Chinese website!