Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 729
Alexander Duchene Avatar asked Mar 05 '13 23:03

Alexander Duchene


2 Answers

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.

like image 94
Jonathan Wakely Avatar answered Oct 26 '22 00:10

Jonathan Wakely


Wrap x in std::ref when you create the thread.

If every time you created a std::thread it took all variables by reference, think what would happen: if you passed a stack-local variable in, it would be a dangling reference, and undefined behavior would result if the thread outlived the scope of that automatic storage variable. This would happen a lot in practice, and result in many bugs. Instead, std::thread by default takes (marshals via perfect forwarding) all arguments (including variables) by value.

The std::future could silently work when calling your worker function by passing in a thread-local lvalue copy of x, but that would be pretty confusing: the worker task would edit x that you thought you passed by reference, and it wouldn't show up in the x outside of the task. Instead, it helpfully gives you that error message. You should be thanking your lucky stars for it!

In order to indicate that you really really want to not take something by value, you wrap it in std::ref, and now it is passed all the way to the worker function as a reference. In this case, you are responsible for managing the lifetime of the reference so that the data referred to lasts at least as long as the std::future's worker task needs it.

like image 30
Yakk - Adam Nevraumont Avatar answered Oct 25 '22 23:10

Yakk - Adam Nevraumont