Home > Article > Backend Development > Why Does Passing a Class Object by Reference to std::thread Still Trigger the Copy Constructor?
std::thread Passing by Reference Invokes Copy Constructor
Issue:
When passing an object of class Log to an std::thread by reference, a compiler error occurs, despite expectations that reference passing should bypass the copy constructor. Conversely, passing the object by pointer resolves the issue.
Explanation:
The underlying reason for this behavior is that std::thread requires its arguments to be passed by value. Passing by reference, as in Log &logger, has the same effect as passing a pointer, i.e., it still requires a copy constructor to generate a copy of the object to be passed to the thread.
Solution:
To regain reference semantics, sử dụng std::reference_wrapper:
std::thread newThread(session, &sock, std::ref(logger));
Note:
The above is the detailed content of Why Does Passing a Class Object by Reference to std::thread Still Trigger the Copy Constructor?. For more information, please follow other related articles on the PHP Chinese website!