c++ - 为什么在C++中多了一个&来传递非静态成员函数的地址给线程?

标签 c++ gcc mingw pointer-to-member

据我了解,函数名称本身就是指向它的指针。

因此,当我有一个函数时,我可以通过简单地将它的地址传递给线程构造函数来创建一个线程,如下所示:

void thread_function {

}

std::thread threadObj1(thread_function);

我的困惑是在将非静态成员函数的地址传递给线程时。例如:

class ClassA
{
  public:
  void nonstatic_function()
  {

  }
};

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

传递这样一个函数的地址有两种方式:

ClassA::nonstatic_function

&ClassA::nonstatic_function

为什么多了一个&?如果确实需要它,那么为什么即使没有它编译器也不会报错?

最佳答案

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

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

对于非静态成员函数,没有到成员指针的隐式转换。指向成员的指针与自由函数指针有着根本的不同,因为它不能在不提供对象实例的情况下被调用。

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

我猜你正在使用一个带有非标准扩展的编译器来允许在这种情况下省略 & 。我相信旧版本的 MSVC 允许省略它;和 gcc/Windows defaults to allowing this for MSVC compatibility

关于c++ - 为什么在C++中多了一个&来传递非静态成员函数的地址给线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553411/

相关文章:

performance - BASH:一次设置多个变量/性能

c++ - 在 Windows 中使用 MinGW 的谷歌 Protocol Buffer

c++ - 使用自定义比较功能使用std::sort()对 vector 字符串进行排序时遇到问题

c++ - 使用模板和/或 constexpr 在编译时构建函数

c - 如何验证函数 X() 是从函数 Y() 而不是从函数 Z() 调用的?

compiler-errors - 虽然放在mingw文件夹中,但找不到包含的库头文件

c++ - 在 Windows 8 上使用 Code::Blocks 设置 SFML

c++ - QSerialPort 5.2 中的 SerialPortError?

c++ - 从文件中读取文本并将其作为代码运行

linux - 我如何告诉 `gar` 或 `ar` 输出 `elf32-i386` 输出?