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

谁都会走 提交于 2019-11-26 02:25:12

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/8299545/why-does-passing-object-reference-arguments-to-thread-function-fails-to-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!