4

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?

M.M
  • 138,810
  • 21
  • 208
  • 365
softwarelover
  • 1,009
  • 1
  • 10
  • 22

2 Answers2

3

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
0

std::bind helps you.

ClassA instance;
std::thread threadObj2(std::bind(&ClassA::nonstatic_function, &instance));
vezunchik
  • 3,669
  • 3
  • 16
  • 25