Home > Backend Development > C++ > Why Does `std::thread` Not Bypass Copy Constructors When Passing Arguments by Reference?

Why Does `std::thread` Not Bypass Copy Constructors When Passing Arguments by Reference?

DDD
Release: 2024-11-27 12:04:09
Original
986 people have browsed it

Why Does `std::thread` Not Bypass Copy Constructors When Passing Arguments by Reference?

std::thread and Copy Constructors: Understanding the Pass-by-Reference Conundrum

std::thread, an integral part of modern C multithreading capabilities, presents a dilemma when passing objects by reference. This is due to a fundamental difference between the way the language handles references and how std::thread processes its arguments.

When passing an object by reference, we expect the copy constructor to be bypassed as the reference acts as an alias to the original object. However, this assumption does not hold true for std::thread. Here's why.

std::thread's Argument Handling

Contrary to our expectations, std::thread passes its arguments by value. A function object is declared, accepting the same parameters as the thread, and then invoked with the provided arguments. This means that each argument is copied into the function object, even if it's passed as a reference.

Private Copy Constructors and Failed Compilation

In the provided code, the Log class intentionally disables the copy constructor by making it private. When std::thread attempts to copy the logger into the function object, it triggers a compilation error as the private copy constructor is inaccessible.

Resolving the Issue with std::reference_wrapper

To regain reference semantics when passing arguments to std::thread, we can employ std::reference_wrapper. Wrapping the reference with std::reference_wrapper ensures that the function object receives a reference to the original object, avoiding the pitfalls of value copying.

Code Using std::reference_wrapper

std::thread newThread(session, &sock, std::ref(logger));
Copy after login

In this corrected example, the compiler is able to correctly create the std::thread object as the logger is now wrapped in std::reference_wrapper, preserving its reference status.

The above is the detailed content of Why Does `std::thread` Not Bypass Copy Constructors When Passing Arguments 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template