0

Similar to this question: Start thread with member function and this one: std::thread calling method of class

However I have the following:

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

Then I have to call myFunction() from a different place in a new thread, but the following does not compile (and I can't think of anything else to try):

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

1 Answers1

1

Pass std::ref(myInstance). Note that std::thread constructor will make a copy of the arguments passed to it (see here), and you can't copy a myAbstractClass.

(Then, all of this will still work because std::thread functionality is described in terms of std::invoke, which unwraps the std::reference_wrapper obtained by std::ref and calls the pointer to member function onto it. See here).

peppe
  • 21,934
  • 4
  • 55
  • 70