#include<iostream>
#include<thread>
using namespace std;
void f1(double& ret) {
ret=5.;
}
int main() {
double ret=0.;
thread t1(f1, ret);
t1.join();
cout << "ret=" << ret << endl;
}
上面的代码编译失败并出现以下错误消息:
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
In file included from /usr/local/include/c++/5.3.0/thread:39:0,
from main.cpp:2:
/usr/local/include/c++/5.3.0/functional: In instantiation of 'struct std::_Bind_simple<void (*(double))(double&)>':
/usr/local/include/c++/5.3.0/thread:137:59: required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(double&); _Args = {double&}]'
main.cpp:11:21: required from here
/usr/local/include/c++/5.3.0/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/local/include/c++/5.3.0/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'
_M_invoke(_Index_tuple<_Indices...>)
^
我知道我可以std::ref()
用来传递论点。但是,如果我按值传递,为什么会出现错误,因为应该只按值thread
复制参数并传递存储在线程内的一些对象以与 function 的引用参数绑定。f1
我觉得如果我能理解这result_of
是在做什么以及为什么会出错,我就能更好地理解原因。那么任何人都可以引导我完成错误消息吗?尤其是std::_Bind_simple<void (*(double))(double&)>
和的含义std::result_of<void (*(double))(double&)>
。
编辑:我知道如果我传递一个值,线程只会在副本上工作,并且在线程返回后没有效果。这不是我关心的问题。我想知道为什么它现在给出错误,但它没有给 SO 上的其他帖子给出错误,如下所示:指针和引用之间的差异作为线程参数