为什么会有额外的&将非静态成员函数的地址传递给C ++中的线程? [英] Why is there an extra & to pass the address of a non-static member function to a thread in C++?

查看:85
本文介绍了为什么会有额外的&将非静态成员函数的地址传递给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?

推荐答案

据我了解,函数本身的名称用作指向它的指针.

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

此行为是从C继承的,仅适用于自由函数或静态成员函数.

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?

我猜您正在使用具有非标准扩展名的编译器来允许在这种情况下省略&.我相信MSVC的较旧版本允许将其省略;和 gcc/Windows默认情况下允许与MSVC兼容.

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.

这篇关于为什么会有额外的&将非静态成员函数的地址传递给C ++中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆