如何对涉及用户定义 class 返回非 void 类型的成员函数的线程使用引用包装 (c++)

How to use reference wrapping for a thread involving a member function of user defined class returning a non void type(c++)

我无法使 wait/get 未来机制与用户定义的成员函数一起工作 class 返回非空类型。

我在下面写了一个非常简单的例子,指令里面的引用换行

std::future<int> fut = std::async( &BasicClass::funcInt, std::ref(anObject) );

编译时失败

#include <iostream> // cout
#include <future>   // async, future

using std::cout;
using std::async;
using std::future;

class BasicClass
{ public:
    int funcInt(){return 119;}
    void funcVoid(){cout << "\nvoid funcVoid()";}
};

int main()
{
  BasicClass anObject;

  std::thread thread1( &BasicClass::funcVoid, std::ref(anObject));
  thread1.join();

  std::future<int> fut = std::async( &BasicClass::funcInt, std::ref(anObject));
  fut.wait();
  int a = fut.get();
  return 0;
}

对于具有返回 void 类型的成员函数的线程,引用包装工作正常。

  std::thread thread1( &BasicClass::funcVoid, std::ref(anObject));

你能解释一下这个问题吗?

谢谢

std::async(除其他外)使用的神奇伪函数 INVOKE 不处理与 reference_wrapper 配对的指向成员的指针。 std::thread 也应该使用 INVOKE,但 libstdc++(GCC 的标准库)的实现由于其实现方式而恰好不会阻塞此特定组合。 Clang 的标准库 libc++ 将无法为两者编译。

直到LWG issue 2219的决议被投票进入工作文件并实施,只需使用指针: std::async(&BasicClass::funcInt, &anObject);