Home  >  Article  >  Backend Development  >  Why Does `std::thread` Appear to Call the Copy Constructor When Passing by Reference?

Why Does `std::thread` Appear to Call the Copy Constructor When Passing by Reference?

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 10:08:02942browse

Why Does `std::thread` Appear to Call the Copy Constructor When Passing by Reference?

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.

The above is the detailed content of Why Does `std::thread` Appear to Call the Copy Constructor When Passing by Reference?. 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