I tried run a function, which starts thread, but i recived error :
error: invalid use of non-static member function ‘void Sniffer::f1(int)’
code:
#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;
}
Any other way, to fix it without change a function, on static function?
In C++ member functions have an implicit first parameter that binds to this
. When creating a thread, the this
pointer must be passed. You must also qualify the member function with a class name. The correct thread constructor in your case would look like this:
std::thread t1( &Sniffer::f1, this, y );
Alternatively, you could pass a lambda to the thread constructor instead:
std::thread t1([this, y] // capture the this pointer and y by value
{
this->f1(y);
});
When you create std::thread
it doesn't capture the this
pointer for you. You would have to include the this
pointer when creating the thread, or you could use a lambda that captures this
or captures everything by reference.
eg:
void Sniffer::f2()
{
int y = 5;
std::thread t1(&Sniffer::f1, this, y);
t1.join();
}
or:
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();
}
Of course, if you capture this
then you don't need to mention it in the body of the lambda and without parameters needed we can remove the ()
which simplifies to:
void Sniffer::f2()
{
int y = 5;
std::thread t1([this,y]{f1(y); });
t1.join();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.