Home >Backend Development >C++ >Why Does Passing a Class Object by Reference to std::thread Still Trigger the Copy Constructor?

Why Does Passing a Class Object by Reference to std::thread Still Trigger the Copy Constructor?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 15:54:01422browse

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:

  1. Ensure that the lifetime of the referenced object (logger in this case) exceeds that of the thread.
  2. In the provided code, Log's copy constructor is private, preventing the creation of additional copies.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn