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

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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 the thread constructor will only copy a pointer, not a Fred object.
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.
hmm never mind, i was wrong. When i pass just f, the copy constructor is being called 3 times. Any idea why 3 times?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.