有些人似乎使用 boost::bind() 函数启动 boost::threads,例如在以下问题的公认答案中:
Using boost thread and a non-static class function
而其他人根本不使用它,例如在这个问题中获得最多赞成票的答案:
Best way to start a thread as a member of a C++ class?
那么,如果存在差异,那有什么区别呢?
最佳答案
从下面编译并给出预期输出的代码可以看出,boost::bind 对于将 boost::thread 与自由函数、成员函数和静态成员函数一起使用是完全不必要的:
#include <boost/thread/thread.hpp>
#include <iostream>
void FreeFunction()
{
std::cout << "hello from free function" << std::endl;
}
struct SomeClass
{
void MemberFunction()
{
std::cout << "hello from member function" << std::endl;
}
static void StaticFunction()
{
std::cout << "hello from static member function" << std::endl;
}
};
int main()
{
SomeClass someClass;
// this free function will be used internally as is
boost::thread t1(&FreeFunction);
t1.join();
// this static member function will be used internally as is
boost::thread t2(&SomeClass::StaticFunction);
t2.join();
// boost::bind will be called on this member function internally
boost::thread t3(&SomeClass::MemberFunction, someClass);
t3.join();
}
输出:
hello from free function
hello from static member function
hello from member function
构造函数中的内部绑定(bind)为您完成所有工作。
刚刚添加了一些关于每种函数类型会发生什么的额外注释。 (希望我已经正确阅读了源代码!)据我所知,在外部使用 boost::bind 不会导致它也加倍并在内部被调用,因为它将按原样传递。
关于c++ - 使用或不使用 boost::bind() 创建一个 boost::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13742648/