0

In below code, at thread t(&Fred::hello) i am getting an error that the term does not evaluate to a function taking 0 arguments. What is the issue?

#include <iostream>
#include <thread>

using namespace std;

class Fred
{
public:

virtual void hello();

};

void Fred::hello()
{
cout << "hello" << endl;
}

int main()
{
thread t (&Fred::hello);
t.join();

return 0;
}
Jimm
  • 8,165
  • 16
  • 69
  • 118

1 Answers1

4

A non-static member function of class T needs to be called on an instance of T, and takes an implicit first parameter of type T* (or const, and/or volatile T*).

So

Fred f;
f.hello()

is equivalent to

Fred f;
Fred::hello(&f);

So when you pass a non-static member function to a thread constructor, you must pass the implicit first argument too:

Fred f;
std::thread t(&Fred::hello, &f);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • That is great explaination. But is there a version of thread constructor which can use emplace semantics? It seems a waste that i have to do pass `&f`, only for the thread constructor to copy it again? – Jimm May 10 '13 at 15:43
  • @Jimm the thread constructor will only copy a *pointer*, not a `Fred` object. – juanchopanza May 10 '13 at 15:45
  • I just tried passing `f` and not `&f`, such as `std::thread t(&Fred:hello, f)` and it seems to be working. Plus constructor is called only once. In this case, thread constructor seems to be avoiding copying of f. – Jimm May 10 '13 at 15:54
  • hmm never mind, i was wrong. When i pass just `f`, the copy constructor is being called 3 times. Any idea why 3 times? – Jimm May 10 '13 at 15:58