Home > Backend Development > C++ > Why Does Passing Object References to Threads Cause Compilation Errors, and How Can `std::ref` Help?

Why Does Passing Object References to Threads Cause Compilation Errors, and How Can `std::ref` Help?

Barbara Streisand
Release: 2024-12-01 01:42:09
Original
778 people have browsed it

Why Does Passing Object References to Threads Cause Compilation Errors, and How Can `std::ref` Help?

Understanding the Compilation Failure When Passing Object References to Thread Functions

When attempting to pass a reference to an object, such as a std::ostream, to a thread function, compilation may fail due to a deleted constructor. This issue arises because threads typically copy their arguments to avoid referential aliasing concerns.

To bypass the compilation error, it is essential to utilize std::ref (or std::cref for constant references). std::ref allows you to wrap a reference with value semantics, enabling you to copy the wrapper safely.

std::thread t(foo, std::ref(std::cout));
Copy after login

Here, the std::ref wrapper provides a copyable object that contains the reference to std::cout. Therefore, the thread can successfully copy it and execute the function correctly.

Remember that this code will only function as long as the referenced object remains valid. It is crucial to ensure that the object's lifetime exceeds the execution duration of the thread. Failure to adhere to this may result in undefined behavior.

The above is the detailed content of Why Does Passing Object References to Threads Cause Compilation Errors, and How Can `std::ref` Help?. 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