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 originalintis put in the thread stack, andxreferences this copy; we see1and1.On the other hand, with
std::cref(),xstill references the original; we see1and2.