I have two functions
void f(const int &x) {}
void g(int& x) {}
I can make
int x = 0;
std::thread t1(f, x);
But I can't create std::thread t2(g, x)
, in this case i need make std::ref(x)
instead of just x
, why is it necessary?
And why it possible to create t1
without std::cref
?
Your
f()
function does not work as you expect withoutstd::cref()
.Although
f()
does not intent to change the value behindx
, it does not mean that the value behind this reference cannot be mutated elsewhere.In this example, without
std::cref()
a copy of the originalint
is put in the thread stack, andx
references this copy; we see1
and1
.On the other hand, with
std::cref()
,x
still references the original; we see1
and2
.