1
我有一個成員函數MyClass::doStuff(QString & str)
開始帶有參數的成員函數在一個單獨的線程
我試圖調用該函數從一個線程是這樣的:
std::thread thr(&MyClass::doStuff, this);
然而,這會導致錯誤:
/usr/include/c++/4.8.2/functional:1697: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (MyClass::*)(QString&)>(MyClass*)>’ typedef typename result_of<_Callable(_Args...)>::type result_type;
所以我試圖給它的參數:
QString a("test");
std::thread thr(&MyClass::doStuff(a), this);
但是,導致此錯誤:lvalue required as unary ‘&’ operand
我怎麼會去運行成員函數的參數,從一個單獨的線程?
問題:因爲'doStuff'索要參考,但它運行在另一個線程中,沒有什麼能阻止你刪除'a',並且你最終會得到一個UB? – Ceros
@Ceros當然,如果你刪除了一個別的東西正在使用的變量會有麻煩:) – Galik
在這種情況下'std :: ref'的目的是什麼? – Ceros