Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c++ - Invalid initialization of non-const reference with C++11 thread?

I'm getting an error about

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

from

#include <thread>
#include <iostream>

using namespace std;

void func(int& i){
    cout<<++i<<endl;
}

int main(){
    int x=7;
    thread t(func,x);
    t.join();
    return 0;
}

I understand that I can't do thread(func, 4) but x is a variable, not a temporary.

I am using gcc 4.7 with -std=c++11 -pthread

Why is this error occurring?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...