为什么 std::async 不能与接收抽象 class 引用作为参数的函数一起使用?

Why std::async cannot be used with functions that receive a reference to an abstract class as a parameter?

我正在尝试通过 std::async 执行接收参数的函数,该参数是对抽象 class 的引用,但由于某些原因似乎无效。另一方面,如果我用指针替换提到的引用,一切正常。

为什么会这样?通常将抽象 class 参数作为指针传递更好吗?

请参阅以下示例:

错误使用std::async

#include <iostream>
#include <future>

class AbsClass {
  public:
    virtual int f() = 0;
};

class ImplClass : public AbsClass {
  public:
    int f() override { return 21; }
};

int func(AbsClass &asbclass) {
  return 210 + asbclass.f();
}

int main() {
  ImplClass ic;
  AbsClass &ac = ic;

  // This causes a compilation failure:
  std::future<int> res = std::async(&func, ac);

  std::cout << res.get() << std::endl;
}

显示失败

/usr/include/c++/7/future:1745:5: error: invalid abstract parameter type ‘AbsClass’
main.cpp:4:7: note:   because the following virtual functions are pure within ‘AbsClass’:
 class AbsClass {
       ^~~~~~~~
main.cpp:6:17: note:    virtual int AbsClass::f()
     virtual int f() = 0;

正确使用std::async

#include <iostream>
#include <future>

class AbsClass {
  public:
    virtual int f() = 0;
};

class ImplClass : public AbsClass {
  public:
    int f() override { return 21; }
};

int func(AbsClass *asbclass) {
  return 210 + asbclass->f();
}

int main() {
  ImplClass ic;
  AbsClass &ac = ic;

  std::future<int> res = std::async(&func, &ac);

  std::cout << res.get() << std::endl;
}

需要存储参数,这意味着它们被复制了。并且引用无法复制。

因此 reference wrapper was introduced, that can store references while also being able to be copied. You can use it with the helper function std::ref and std::cref:

std::future<int> res = std::async(&func, std::ref(ac));  // Pass ac by reference