When passing objects to std::thread, arguments are typically copied into the thread, rather than being referenced. This behavior contradicts the expectation that passing by reference should avoid copy construction. The confusion stems from the distinction between references and pointers in C .
In C , passing an object by reference generally means passing its address, which is equivalent to passing a pointer. However, std::thread has a specific implementation that requires its arguments to be copied by value.
To achieve reference semantics, use std::reference_wrapper as follows:
std::thread newThread(session, &sock, std::ref(logger));
This way, logger is not copied, but rather its reference is passed to the thread. Note that logger must outlive the thread.
The use of std::move() is not recommended in this case because std::thread expects arguments to be copied. Moving the object would transfer ownership of its memory to the thread, which may not be desired.
If your code was previously working with std::move() but now fails, it's possible that your version of the compiler does not fully implement C 11. Consider updating your compiler for enhanced C 11 support.
The above is the detailed content of Why Does Passing an Object by Reference to std::thread Invoke the Copy Constructor?. For more information, please follow other related articles on the PHP Chinese website!