亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過引用將對象傳遞給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 關注
  • 575 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號