為什么創建時不能通過引用傳遞對象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)。

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
明智地,捕獲默認為按值捕獲,因為如果參數在線程可以讀取它之前就消失了,那么事情將徹底失敗。您需要明確要求這種行為,以便可以表明您有責任確保引用目標仍然有效。
- 3 回答
- 0 關注
- 575 瀏覽
添加回答
舉報
0/150
提交
取消