简体   繁体   English

boost :: thread无效使用非静态成员函数

[英]boost::thread invalid use of a non-static member function

I'm begining with the boost::thread library and I have a code like this : 我从boost :: thread库开始,我有一个像这样的代码:

Class::Class()
{
    ...
    boost::thread thread_foo(Class::foo);
    ...
}

Class::foo()
{
    //do stuff
}

But when I compile it, I have an "invalid use of a non-static member function" and I don't really know what is wrong because when I look at the doc this is the way to create a thread. 但是,当我编译它时,我“无效地使用了一个非静态成员函数”,我真的不知道出什么问题了,因为当我看文档时,这是创建线程的方式。

I'm sure it's a silly mistake but I just don't see it. 我敢肯定这是一个愚蠢的错误,但我只是看不到它。

Thanks 谢谢

You should send object also. 您还应该发送对象。

boost::thread thread_foo(&Class::foo, this);

or 要么

boost::thread thread_foo(boost::bind(&Class::foo, this));

All non-static member function have a hidden first argument, that is the this pointer in the member function. 所有非静态成员函数都有一个隐藏的第一个参数,即成员函数中的this指针。

If you don't provide the instance to call the member function on, then this will be undefined and you will have undefined behavior . 如果你不提供实例调用的成员函数,那么this将是不确定的,你将有不确定的行为

Statis member functions, on the other hand, does not have this hidden argument, and so can be called without an instance. 另一方面,Statis成员函数没有此隐藏参数,因此可以在没有实例的情况下调用它。

To solve your problem, either listen to the compiler message and make your member function static. 要解决您的问题,请侦听编译器消息并使成员函数静态。 Or you pass an argument to the thread function, and that argument must be the instance to call the function on (normally this ). 或者,您将一个参数传递给线程函数,并且该参数必须是调用该函数的实例(通常为this )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM