2017-04-05 35 views
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

我怎麼會去運行成員函數的參數,從一個單獨的線程?

回答

1

只需將參數添加到線程的構造函數:

QString a("test"); 
std::thread thr(&MyClass::doStuff, this, a); 

當你的函數接受參考你應該使用std::ref()這樣的:

MyClass::doStuff(QString& str) { /* ... */ } 

// ... 

QString a("test"); 
std::thread thr(&MyClass::doStuff, this, std::ref(a)); // wrap references 
+0

問題:因爲'doStuff'索要參考,但它運行在另一個線程中,沒有什麼能阻止你刪除'a',並且你最終會得到一個UB? – Ceros

+0

@Ceros當然,如果你刪除了一個別的東西正在使用的變量會有麻煩:) – Galik

+0

在這種情況下'std :: ref'的目的是什麼? – Ceros

相關問題