使用C ++ 11线程的非const引用的初始化无效? [英] Invalid initialization of non-const reference with C++11 thread?

查看:357
本文介绍了使用C ++ 11线程的非const引用的初始化无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到有关

的错误


错误:无效初始化类型为'int&'的非const引用类型int


  #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;
}



我理解我不能做 thread func,4) x 是一个变量,不是临时变量。



为什么会出现此错误?

>解决方案

std :: thread 构造函数的规范说


效果:构造一个线程类型的对象。新的执行线程执行 INVOKE DECAY_COPY (std :: forward< F& (f)), DECAY_COPY (std :: forward< Args>(args))...)


其中 DECAY_COPY(x)表示调用 decay_copy(x),其中定义为:

  template< class T> typename decay< T> :: type decay_copy(T& v)
{return std :: forward< T> }

这意味着decay参数被复制, em> by value 并失去任何cv-qualification。因为线程运行的目标函数想要通过引用获取其参数,所以您会收到一个编译器错误,说该引用无法绑定到通过值的对象。



这是通过设计,所以默认局部变量传递到 std :: thread 通过值传递(即复制)不通过引用,新线程将不会有超出范围的局部变量的悬挂引用,导致未定义的行为。



如果你知道可以通过引用传递变量需要使用 reference_wrapper 显式地执行此操作,它不会受衰减语义的影响,并且将通过引用目标对象转发变量。您可以使用 std :: ref 创建 reference_wrapper


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?

解决方案

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.

这篇关于使用C ++ 11线程的非const引用的初始化无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆