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

为什么创建时不能通过引用传递对象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...>)

         ^

我已更改为传递指针,但是周围有更好的解决方法吗?


蝴蝶不菲
浏览 491回答 3
3回答

慕妹3146593

reference_wrapper通过使用std::ref显式初始化线程:auto thread1 = std::thread(SimpleThread, std::ref(a));(或std::cref代替std::ref,视情况而定)。根据cppreference中的std:thread注释:线程函数的参数按值移动或复制。如果需要将引用参数传递给线程函数,则必须将其包装(例如,使用std::ref或std::cref)。

饮歌长啸

明智地,捕获默认为按值捕获,因为如果参数在线程可以读取它之前就消失了,那么事情将彻底失败。您需要明确要求这种行为,以便可以表明您有责任确保引用目标仍然有效。
打开App,查看更多内容
随时随地看视频慕课网APP