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

雨燕双飞 提交于 2019-12-12 02:50:42

问题


I'm having trouble making the wait/get future mechanism work with a member function of user defined class returning a non-void type.

I wrote a very simple example below, the reference wrapping inside the instruction

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

fails at compile time

#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;
}

The reference wrapping works find for a thread with a member function returning a void type works fine.

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

Can you explain the issue?

Thanks


回答1:


The magical pseudo-function INVOKE that std::async (among other things) uses doesn't handle pointers-to-member paired with reference_wrappers. std::thread is also supposed to use INVOKE, but libstdc++ (GCC's standard library)'s implementation happens to not choke on this particular combination, due to the way it was implemented. libc++, Clang's standard library, will fail to compile for both.

Until LWG issue 2219's resolution is voted into the working paper and implemented, just use a pointer: std::async(&BasicClass::funcInt, &anObject);



来源:https://stackoverflow.com/questions/31553262/how-to-use-reference-wrapping-for-a-thread-involving-a-member-function-of-user-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!