Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does passing object reference arguments to thread function fails to compile?

I've come to a problem using the new c++11 std::thread interface.
I can't figure out how to pass a reference to a std::ostream to the function that the thread will execute.

Here's an example with passing an integer(compile and work as expected under gcc 4.6) :

void foo(int &i) {     /** do something with i **/     std::cout << i << std::endl; }  int k = 10; std::thread t(foo, k); 

But when I try passing an ostream it does not compile :

void foo(std::ostream &os) {     /** do something with os **/     os << "This should be printed to os" << std::endl; }  std::thread t(foo, std::cout); 

Is there a way to do just that, or is it not possible at all ??

NB: from the compile error it seems to come from a deleted constructor...

like image 520
Benjamin A. Avatar asked Nov 28 '11 17:11

Benjamin A.


People also ask

Can you pass a reference to a thread C++?

In c++11 to pass a referenceto a thread, we have std::ref(). std::thread t3(fun3, std::ref(x)); In this statement we are passing reference of x to thread t3 because fun3() takes int reference as a parameter. If we try to pass 'x' or '&x' it will throw a compile time error.

Can you pass arguments to a thread?

You can only pass a single argument to the function that you are calling in the new thread.


1 Answers

Threads copy their arguments (think about it, that's The Right Thing). If you want a reference explicitly, you have to wrap it with std::ref (or std::cref for constant references):

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

(The reference wrapper is a wrapper with value semantics around a reference. That is, you can copy the wrapper, and all copies will contain the same reference.)

As usual, this code is only correct as long as the object to which you refer remains alive. Caveat emptor.

like image 178
Kerrek SB Avatar answered Oct 13 '22 09:10

Kerrek SB