-1

Say I have an object called myObject of class myClass. It has a function

void myFunction()

What is the syntax to call this function with a thread?

I tried

std::thread myThread(myObject.myFunction) 

but I'm given a syntax error and can't seems to find the correct syntax.

The error message is:

function "std::thread::thread(const std::thread &)" cannot be referenced -- it is a deleted function

Thanks for any help.

Alex L
  • 115
  • 11

3 Answers3

1

You can write:

std::thread myThread(std::bind(&myClass::myFunction, myObject));

Being, myClass the class name of myObject. This is the syntax for a pointer-to-member-function.

Also, you can add any other argument your myFunction requires just after myObject.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
0

according to GCC , here is the error : http://coliru.stacked-crooked.com/a/4fcba365c9b25d1e

which makes sense, because member function is bound to this pointer , member variabes and many more. I'd go with lambda expression :

std::thread t ([&]{
   myObject.myFunction();
}) 

working example : http://coliru.stacked-crooked.com/a/0be834a7249bfac9

btw, this practice of wrapping everything with anonymous function is very common in JavaScript, and should be used also here

David Haim
  • 25,446
  • 3
  • 44
  • 78
0

Possible duplicate.

std::thread myThread(&myClass.myFunction, myObject) 
Community
  • 1
  • 1
M.L.
  • 728
  • 4
  • 12