为什么传递对象引用参数到线程函数无法编译?

问题描述:

我使用新的c ++ 11 std :: thread 接口出现问题。

我无法弄清楚将一个 std :: ostream 的引用传递给线程将执行的函数。

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.

传递一个整数(按照gcc 4.6中的预期编译和工作):

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);

但是当我尝试传递一个ostream时,它不会编译:

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

线程复制他们的参数(想想,这是正确的事情)。如果你想显式地引用一个引用,你必须用 std :: ref (或 std :: cref 常量引用):

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.