Home >Backend Development >C++ >How to Correctly Pass Object References to C 11 std::thread Functions?

How to Correctly Pass Object References to C 11 std::thread Functions?

DDD
DDDOriginal
2024-11-26 11:47:10456browse

How to Correctly Pass Object References to C  11 std::thread Functions?

Passing Object References to Thread Function

When working with the C 11 std::thread interface, one may encounter issues when attempting to pass object references as arguments to the thread function. This problem arises even when passing simple integers, as observed in the following code:

void foo(int& i) {
    // Do something with i
    std::cout << i << std::endl;
}

int k = 10;
std::thread t(foo, k);

This code compiles and executes as expected, but passing an std::ostream reference results in a compilation error:

void foo(std::ostream& os) {
    // Do something with os
    os << "This should be printed to os" << std::endl;
}

std::thread t(foo, std::cout);

Cause of the Compilation Error

The compilation error stems from the deleted constructor for std::thread. By default, threads copy their arguments, making it impossible to pass a reference directly.

Solution: Using std::ref

To pass a reference as an argument to a thread function, you must wrap it using std::ref (or std::cref for constant references). This creates a reference wrapper with value semantics, allowing for copies of the reference to exist.

std::thread t(foo, std::ref(std::cout));

By using std::ref, you can pass a reference to the thread function, enabling direct manipulation of the passed object. However, it's crucial to ensure that the referenced object remains alive for the duration of the thread's execution.

The above is the detailed content of How to Correctly Pass Object References to C 11 std::thread Functions?. 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