Passing Object Reference Arguments to Thread Functions: A Constructor Issue
In C 11, the std::thread interface allows for the creation of lightweight threads. One common task is passing arguments to these thread functions, but difficulties may arise when attempting to pass object references.
Consider the following example:
void foo(int &i) { std::cout << i << std::endl; } int k = 10; std::thread t(foo, k);
This code successfully compiles and runs, as integers are copied into the thread function. However, passing an std::ostream object reference doesn't compile:
void foo(std::ostream &os) { os << "This should be printed to os" << std::endl; } std::thread t(foo, std::cout);
The error indicates a missing or inaccessible constructor.
Solution: Using std::ref
Threads copy their arguments by default. To pass a reference explicitly, an alternative approach is needed. This is where std::ref comes in. It wraps an object reference in a value-semantics wrapper.
By using std::ref, the thread function receives a copy of the wrapper, but the wrapped reference remains the same:
std::thread t(foo, std::ref(std::cout));
This enables the thread function to access and modify the original object, allowing for the desired functionality.
It's crucial to note that the object being referenced must remain accessible throughout the thread's execution. If it's deleted or modified before the thread finishes, unexpected behavior or crashes might occur.
The above is the detailed content of How Can I Safely Pass Object References to C 11 Threads?. For more information, please follow other related articles on the PHP Chinese website!