【问题标题】:Start thread with derived class's member function使用派生类的成员函数启动线程
【发布时间】:2017-09-04 13:59:41
【问题描述】:

类似于这个问题:Start thread with member function 和这个问题:std::thread calling method of class

但是我有以下几点:

#include <thread>
#include <iostream>
class myAbstractClass {
public:
  virtual void myFunction() = 0;//abstract class
}

class myFirstClass : public myAbstractClass {
public:
  void myFunction() { std::cout << "First class here";}
}

class mySecondClass : public myAbstractClass {
public:
  void myFunction() { std::cout << "Second class here";}
}

然后我必须从新线程的不同位置调用myFunction(),但以下内容无法编译(我想不出其他任何尝试):

public void callMemberFunctionInThread(myAbstractClass& myInstance) {
  std::thread myThread (&myAbstractClass::myFunction, myInstance);
  //supposed to call myInstance.myFunction() on myThread
}

【问题讨论】:

  • “不编译”不是很具体。您收到了哪些错误消息?
  • Intellisense 不会抱怨,编译开始,然后它在位于 C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include 的文件 tuple 中给出 C2259 'myAbstractClass': cannot instantiate abstract class(第 199 行)
  • std::ref(myInstance)?
  • 请先修复您的程序,使其成为minimal reproducible example。这里有很多琐碎的语法错误。
  • 如果派生类应该覆盖它,抽象类成员函数应该是virtual。不知道这是否适用于std::thread

标签: c++ multithreading oop c++11 derived-class


【解决方案1】:

通过std::ref(myInstance)。请注意,std::thread 构造函数将复制传递给它的参数(请参阅here),您不能复制myAbstractClass

(那么,所有这些仍然可以工作,因为std::thread 功能是根据std::invoke 描述的,它解开std::ref 获得的std::reference_wrapper 并将指向成员函数的指针调用到它上面。见@987654322 @)。

【讨论】:

    猜你喜欢
    • 2021-09-25
    相关资源
    最近更新 更多