softwarelover
softwarelover

Reputation: 1019

Why is there an extra & to pass the address of a non-static member function to a thread in C++?

As I understand, the name of a function itself serves as a pointer to it.

Therefore, when I have a function, I can create a thread by simply passing its address to the thread constructor, like below:

void thread_function {

}

std::thread threadObj1(thread_function);

My confusion is while passing the address of a non-static member function to a thread. For example:

class ClassA
{
  public:
  void nonstatic_function()
  {

  }
};

ClassA instance;
std::thread threadObj2(ClassA::nonstatic_function, &instance);

Passing the address of such a function is done in two ways:

ClassA::nonstatic_function

&ClassA::nonstatic_function

Why is there an extra &? If it is indeed needed, then how come the compiler does not complain even without it?

Upvotes: 4

Views: 207

Answers (2)

ZenMaster
ZenMaster

Reputation: 1

std::bind helps you.

ClassA instance;
std::thread threadObj2(std::bind(&ClassA::nonstatic_function, &instance));

Upvotes: 0

M.M
M.M

Reputation: 141638

As I understand, the name of a function itself serves as a pointer to it.

This behaviour was inherited from C and only applies to free functions or static member functions.

For non-static member functions there is no implicit conversion to pointer-to-member. A pointer-to-member is a fundamentally different thing from a free function pointer because it can't be called without also providing an object instance.

If it is indeed needed, then how come the compiler does not complain even without it?

I guess you are using a compiler with a non-standard extension to allow the & to be omitted in this case. I believe older versions of MSVC allowed it to be omitted; and gcc/Windows defaults to allowing this for MSVC compatibility.

Upvotes: 3

Related Questions