我將一個私有變數從一個類函式傳遞給一個執行不屬于類的函式的執行緒。該函式呼叫在正常執行時沒有問題,但是當我嘗試使用單獨的執行緒執行它時,我收到錯誤訊息“靜態斷言失敗”。
有誰知道我在這里做錯了什么?
我在下面添加了一個示例程式,它do_something()從一個類 ( ) 中呼叫一個函式 ( ),該類 ( ) 啟動一個帶有非成員函式 ( )A的執行緒 ( )。th1outside()
#include <iostream>
#include <vector>
#include <thread>
void outside(std::vector<int>& array) {
for (int i = 0; i < array.size(); i ) {
printf("array[%d] = %d\n", i, array[i]);
}
}
class A {
public:
void do_something();
private:
std::vector<int> array = { 3, 4, 5 };
};
void A::do_something() {
outside(this->array); // This works.
std::thread th1(outside, this->array); // This doesn't work.
th1.join();
}
int main() {
A example;
example.do_something();
return 0;
}
該程式的編譯導致以下錯誤訊息:
In file included from main.cpp:3:
/usr/include/c /9/thread: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>&); _Args = {A*, std::vector<int, std::allocator<int> >&}; <template-parameter-1-3> = void]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',20)">main.cpp:20:47</span>: required from here
/usr/include/c /9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
120 | typename decay<_Args>::type...>::value,
| ^~~~~
/usr/include/c /9/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (*)(std::vector<int, std::allocator<int> >&), A*, std::vector<int, std::allocator<int> > > >’:
/usr/include/c /9/thread:131:22: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>&); _Args = {A*, std::vector<int, std::allocator<int> >&}; <template-parameter-1-3> = void]’
<span class="error_line" onclick="ide.gotoLine('main.cpp',20)">main.cpp:20:47</span>: required from here
/usr/include/c /9/thread:243:4: error: no type named ‘type’ in ‘struct std::thread::_Invoker >&), A*, std::vector > > >::__result >&), A*, std::vector > > >’
243 | _M_invoke(_Index_tuple<_Ind...>)
| ^~~~~~~~~
/usr/include/c /9/thread:247:2: error: no type named ‘type’ in ‘struct std::thread::_Invoker >&), A*, std::vector > > >::__result >&), A*, std::vector > > >’
247 | operator()()
| ^~~~~~~~
uj5u.com熱心網友回復:
傳遞給建構式的所有值std::thread都被移動或復制。
您可以在檔案中找到它。
執行緒函式的引數按值移動或復制。如果需要將參考引數傳遞給執行緒函式,則必須對其進行包裝(例如,使用 std::ref 或 std::cref)。
如果你想到這里建構式的呼叫
std::thread th1(outside, this->array);
如果您希望陣列在此處按值或通過參考傳遞,則無法明確說明。您可能會爭辯說它應該查看函式簽名并默認使用簽名所做的任何事情,但這也可能會造成混淆。
似乎決定總是假設復制/移動,如果您想通過 ref 傳遞,您需要使用std::ref/明確說明它std::cref。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/532696.html
標籤:C 多线程
上一篇:Chrome擴展程式錯誤
