Home > Backend Development > C++ > 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
Release: 2024-11-15 10:08:02
Original
1023 people have browsed it

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));
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template