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

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.

Leave a Comment