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

别说谁变了你拦得住时间么 提交于 2020-01-21 07:32:06

问题


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?


回答1:


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.




回答2:


std::bind helps you.

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


来源:https://stackoverflow.com/questions/56553411/why-is-there-an-extra-to-pass-the-address-of-a-non-static-member-function-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!