[英]Invalid use of non-static member function c++ thread linux
我嘗試運行一個函數,該函數啟動線程,但是我收到錯誤消息:
error: invalid use of non-static member function ‘void Sniffer::f1(int)’
碼:
#include "library.hpp"
class Sniffer
{
void f1( int x );
void f2();
};
void Sniffer::f1( int x )
{
while (true)
{
sleep(x);
std::cout << 1 << std::endl;
}
}
void Sniffer::f2()
{
int y = 5;
std::thread t1( f1, y );
t1.join();
}
int main()
{
return 0;
}
還有其他方法可以在不更改功能的情況下在靜態功能上進行修復嗎?
在C ++中,成員函數具有綁定到this
的隱式第一個參數。 創建線程時,必須傳遞this
指針。 您還必須使用類名稱限定成員函數。 在您的情況下,正確的線程構造函數將如下所示:
std::thread t1( &Sniffer::f1, this, y );
或者,您可以改為將lambda傳遞給線程構造函數:
std::thread t1([this, y] // capture the this pointer and y by value
{
this->f1(y);
});
當您創建std::thread
它不會為您捕獲this
指針。 創建線程時,必須包含this
指針,或者可以使用lambda來捕獲this
或通過引用捕獲所有內容。
例如:
void Sniffer::f2()
{
int y = 5;
std::thread t1(&Sniffer::f1, this, y);
t1.join();
}
要么:
void Sniffer::f2()
{
int y = 5;
std::thread t1([&,y](){f1(y); }); // captures everything (including this) by reference, captures a copy of y
// becuase y coud go out of scope and be destroyed while the thread could
// continue running (even though in this case that won't happen because the join is in the same scope
t1.join();
}
當然,如果您捕獲了this
則無需在lambda主體中提及它,並且不需要參數,我們可以刪除()
簡化為:
void Sniffer::f2()
{
int y = 5;
std::thread t1([this,y]{f1(y); });
t1.join();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.