std::thread Passes by Value: Copy Constructor Called
Problem:
When passing arguments to a thread using std::thread, passing by reference appears to be calling the copy constructor. This is observed in a case where the passed class has a disabled copy constructor.
Explanation:
By default, std::thread takes its arguments by value. Despite the appearance of a reference in the function signature, the argument is actually copied into the thread object. In the given example, the Log class has its copy constructor disabled, hence the compiler error when passing it by reference.
Solution: Reference Semantics with std::reference_wrapper:
To achieve reference semantics, use std::reference_wrapper to wrap the object and pass it to the thread. This effectively passes a reference to the original object without creating a copy:
std::thread newThread(session, &sock, std::ref(logger));
Thread Function Declarations:
To use std::ref, the corresponding thread function must be modified to accept a std::reference_wrapper:
static void session(tcp::socket *sock, std::reference_wrapper<Log> logger) { std::cout << " session () " << std::endl; }
Lifetime Management:
It's important to ensure that the passed object (in this case, logger) outlives the thread to avoid dangling references.
以上是為什麼「std::thread」在按引用傳遞時會呼叫複製建構子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!