将函子传递给boost ::线程在Visual Studio 2010中失败

passing functor to boost::thread failed in visual studio 2010

本文关键字:Visual Studio 2010 失败 线程 boost      更新时间:2023-10-16

这个简单的代码不会编译:

#include <cstdio>
#include <boost/thread.hpp>
struct ftor{
   void operator()(){ printf("Hello"); }
};
int main()
{
      boost::thread th( ftor() );
     th.join(); //<--- error C2228: left of '.join' must have class/struct/union
}

但是,按照代码进行了很好的编译:

 #include <cstdio>
 #include <boost/thread.hpp>
 struct ftor{
    void operator()(){ printf("Hello"); }
 };
 int main()
 {
     ftor f;
     boost::thread th( f );
     th.join(); 
 }

Q:#1代码有什么问题?

我使用Visual Studio2010。

更新: codepade http://codepad.org/r5aok406显示出更多信息性错误:

Line 19: error: request for member 'join' in 'th', which is of non-class type 'mythread ()(ftor (*)())'
  boost::thread th( ftor() );

th被声明为返回boost :: thread的函数,并将函数指针ftor(*)()作为输入参数。

为了避免这种情况,要么使用C 11的新初始化语法,

  boost::thread th{ ftor() };

或在ftor()周围添加PARATHES。

  boost::thread th( (ftor()) );

这实际上是众所周知的C 故障之一。此问题的原因是C兼容。

  struct TEST;
  TEST a(); //well defined in c, a is a function that returns TEST

c 必须与C兼容,因此Test A()必须是一个函数,但不要将A声明为测试实例并调用其默认构造函数!