为了账号安全,请及时绑定邮箱和手机立即绑定

通过引用将对象传递给C ++ 11中的std :: thread

通过引用将对象传递给C ++ 11中的std :: thread

C++
蝴蝶不菲 2019-12-15 16:12:56
为什么创建时不能通过引用传递对象std::thread?例如,以下代码片段给出了编译错误:#include <iostream>#include <thread>using namespace std;static void SimpleThread(int& a)  // compile error//static void SimpleThread(int a)     // OK{    cout << __PRETTY_FUNCTION__ << ":" << a << endl;}int main(){    int a = 6;    auto thread1 = std::thread(SimpleThread, a);    thread1.join();    return 0;}错误:In file included from /usr/include/c++/4.8/thread:39:0,                 from ./std_thread_refs.cpp:5:/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(int))(int&)>’:/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&); _Args = {int&}]’./std_thread_refs.cpp:19:47:   required from here/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’       typedef typename result_of<_Callable(_Args...)>::type result_type;                                                             ^/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’         _M_invoke(_Index_tuple<_Indices...>)         ^我已更改为传递指针,但是周围有更好的解决方法吗?
查看完整描述

3 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

reference_wrapper通过使用std::ref显式初始化线程:


auto thread1 = std::thread(SimpleThread, std::ref(a));

(或std::cref代替std::ref,视情况而定)。根据cppreference中的std:thread注释:


线程函数的参数按值移动或复制。如果需要将引用参数传递给线程函数,则必须将其包装(例如,使用std::ref或std::cref)。



查看完整回答
反对 回复 2019-12-16
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

明智地,捕获默认为按值捕获,因为如果参数在线程可以读取它之前就消失了,那么事情将彻底失败。您需要明确要求这种行为,以便可以表明您有责任确保引用目标仍然有效。

查看完整回答
反对 回复 2019-12-16
  • 3 回答
  • 0 关注
  • 483 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信