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.
以上是為什麼透過引用 std::thread 傳遞物件會呼叫複製建構子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!