The specification for the std::thread
constructor says
Effects: Constructs an object of type thread. The new thread of execution executes INVOKE (
DECAY_COPY ( std::forward<F>(f)),
DECAY_COPY (std::forward<Args>(args))...)
with the calls to DECAY_COPY being evaluated in the constructing thread.
Where DECAY_COPY(x) means calling decay_copy(x)
where that is defined as:
template <class T> typename decay<T>::type decay_copy(T&& v)
{ return std::forward<T>(v); }
What this means is that the arguments "decay" and are copied, meaning that they are forwarded by value and lose any cv-qualification. Because the target function run by the thread wants to take its parameter by reference, you get a compiler error saying the reference cannot bind to an object passed by value.
This is by design, so that by default local variables passed to a std::thread
get passed by value (i.e. copied) not by reference, so that the new thread will not have dangling references to local variables that go out of scope, leading to undefined behaviour.
If you know it's safe to pass the variables by reference then you need to do so explicitly, using a reference_wrapper
which will not be affected by the "decay" semantics, and will forward the variable by reference to the target object. You can create a reference_wrapper
using std::ref
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…